blob: b68bf9db06854371b93ccb4fbf7658e1d16b61e7 [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
Benjamin Peterson80d50422012-04-03 00:30:38 -04001359 *message = NULL;
1360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001362 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001363 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001365
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001366 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001367 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001369 if (v == Py_None) {
1370 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001372 }
1373 else {
1374 *filename = _PyUnicode_AsString(v);
1375 Py_DECREF(v);
1376 if (!*filename)
1377 goto finally;
1378 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001379
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001380 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001381 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 goto finally;
1383 hold = PyLong_AsLong(v);
1384 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 if (hold < 0 && PyErr_Occurred())
1386 goto finally;
1387 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001388
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001389 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001390 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 goto finally;
1392 if (v == Py_None) {
1393 *offset = -1;
1394 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 } else {
1396 hold = PyLong_AsLong(v);
1397 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 if (hold < 0 && PyErr_Occurred())
1399 goto finally;
1400 *offset = (int)hold;
1401 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001402
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001403 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001404 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001406 if (v == Py_None) {
1407 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001409 }
1410 else {
1411 *text = _PyUnicode_AsString(v);
1412 Py_DECREF(v);
1413 if (!*text)
1414 goto finally;
1415 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001417
1418finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001419 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001421}
1422
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001423void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001424PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001427}
1428
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001429static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001430print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 char *nl;
1433 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001434 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1435 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 for (;;) {
1437 nl = strchr(text, '\n');
1438 if (nl == NULL || nl-text >= offset)
1439 break;
1440 offset -= (int)(nl+1-text);
1441 text = nl+1;
1442 }
1443 while (*text == ' ' || *text == '\t') {
1444 text++;
1445 offset--;
1446 }
1447 }
1448 PyFile_WriteString(" ", f);
1449 PyFile_WriteString(text, f);
1450 if (*text == '\0' || text[strlen(text)-1] != '\n')
1451 PyFile_WriteString("\n", f);
1452 if (offset == -1)
1453 return;
1454 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001455 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001458}
1459
Guido van Rossum66e8e862001-03-23 17:54:43 +00001460static void
1461handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 PyObject *exception, *value, *tb;
1464 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (Py_InspectFlag)
1467 /* Don't exit if -i flag was given. This flag is set to 0
1468 * when entering interactive mode for inspecting. */
1469 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 PyErr_Fetch(&exception, &value, &tb);
1472 fflush(stdout);
1473 if (value == NULL || value == Py_None)
1474 goto done;
1475 if (PyExceptionInstance_Check(value)) {
1476 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001477 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001478 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 if (code) {
1480 Py_DECREF(value);
1481 value = code;
1482 if (value == Py_None)
1483 goto done;
1484 }
1485 /* If we failed to dig out the 'code' attribute,
1486 just let the else clause below print the error. */
1487 }
1488 if (PyLong_Check(value))
1489 exitcode = (int)PyLong_AsLong(value);
1490 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001491 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001492 if (sys_stderr != NULL && sys_stderr != Py_None) {
1493 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1494 } else {
1495 PyObject_Print(value, stderr, Py_PRINT_RAW);
1496 fflush(stderr);
1497 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PySys_WriteStderr("\n");
1499 exitcode = 1;
1500 }
Tim Peterscf615b52003-04-19 18:47:02 +00001501 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 /* Restore and clear the exception info, in order to properly decref
1503 * the exception, value, and traceback. If we just exit instead,
1504 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1505 * some finalizers from running.
1506 */
1507 PyErr_Restore(exception, value, tb);
1508 PyErr_Clear();
1509 Py_Exit(exitcode);
1510 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001511}
1512
1513void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001514PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1519 handle_system_exit();
1520 }
1521 PyErr_Fetch(&exception, &v, &tb);
1522 if (exception == NULL)
1523 return;
1524 PyErr_NormalizeException(&exception, &v, &tb);
1525 if (tb == NULL) {
1526 tb = Py_None;
1527 Py_INCREF(tb);
1528 }
1529 PyException_SetTraceback(v, tb);
1530 if (exception == NULL)
1531 return;
1532 /* Now we know v != NULL too */
1533 if (set_sys_last_vars) {
1534 PySys_SetObject("last_type", exception);
1535 PySys_SetObject("last_value", v);
1536 PySys_SetObject("last_traceback", tb);
1537 }
1538 hook = PySys_GetObject("excepthook");
1539 if (hook) {
1540 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1541 PyObject *result = PyEval_CallObject(hook, args);
1542 if (result == NULL) {
1543 PyObject *exception2, *v2, *tb2;
1544 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1545 handle_system_exit();
1546 }
1547 PyErr_Fetch(&exception2, &v2, &tb2);
1548 PyErr_NormalizeException(&exception2, &v2, &tb2);
1549 /* It should not be possible for exception2 or v2
1550 to be NULL. However PyErr_Display() can't
1551 tolerate NULLs, so just be safe. */
1552 if (exception2 == NULL) {
1553 exception2 = Py_None;
1554 Py_INCREF(exception2);
1555 }
1556 if (v2 == NULL) {
1557 v2 = Py_None;
1558 Py_INCREF(v2);
1559 }
1560 fflush(stdout);
1561 PySys_WriteStderr("Error in sys.excepthook:\n");
1562 PyErr_Display(exception2, v2, tb2);
1563 PySys_WriteStderr("\nOriginal exception was:\n");
1564 PyErr_Display(exception, v, tb);
1565 Py_DECREF(exception2);
1566 Py_DECREF(v2);
1567 Py_XDECREF(tb2);
1568 }
1569 Py_XDECREF(result);
1570 Py_XDECREF(args);
1571 } else {
1572 PySys_WriteStderr("sys.excepthook is missing\n");
1573 PyErr_Display(exception, v, tb);
1574 }
1575 Py_XDECREF(exception);
1576 Py_XDECREF(v);
1577 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001578}
1579
Benjamin Petersone6528212008-07-15 15:32:09 +00001580static void
1581print_exception(PyObject *f, PyObject *value)
1582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 int err = 0;
1584 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001585 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 if (!PyExceptionInstance_Check(value)) {
1588 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1589 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1590 PyFile_WriteString(" found\n", f);
1591 return;
1592 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 Py_INCREF(value);
1595 fflush(stdout);
1596 type = (PyObject *) Py_TYPE(value);
1597 tb = PyException_GetTraceback(value);
1598 if (tb && tb != Py_None)
1599 err = PyTraceBack_Print(tb, f);
1600 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001601 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 {
1603 PyObject *message;
1604 const char *filename, *text;
1605 int lineno, offset;
1606 if (!parse_syntax_error(value, &message, &filename,
1607 &lineno, &offset, &text))
1608 PyErr_Clear();
1609 else {
1610 char buf[10];
1611 PyFile_WriteString(" File \"", f);
1612 if (filename == NULL)
1613 PyFile_WriteString("<string>", f);
1614 else
1615 PyFile_WriteString(filename, f);
1616 PyFile_WriteString("\", line ", f);
1617 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1618 PyFile_WriteString(buf, f);
1619 PyFile_WriteString("\n", f);
1620 if (text != NULL)
1621 print_error_text(f, offset, text);
1622 Py_DECREF(value);
1623 value = message;
1624 /* Can't be bothered to check all those
1625 PyFile_WriteString() calls */
1626 if (PyErr_Occurred())
1627 err = -1;
1628 }
1629 }
1630 if (err) {
1631 /* Don't do anything else */
1632 }
1633 else {
1634 PyObject* moduleName;
1635 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001636 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 assert(PyExceptionClass_Check(type));
1638 className = PyExceptionClass_Name(type);
1639 if (className != NULL) {
1640 char *dot = strrchr(className, '.');
1641 if (dot != NULL)
1642 className = dot+1;
1643 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001644
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001645 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1647 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001648 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 err = PyFile_WriteString("<unknown>", f);
1650 }
1651 else {
1652 char* modstr = _PyUnicode_AsString(moduleName);
1653 if (modstr && strcmp(modstr, "builtins"))
1654 {
1655 err = PyFile_WriteString(modstr, f);
1656 err += PyFile_WriteString(".", f);
1657 }
1658 Py_DECREF(moduleName);
1659 }
1660 if (err == 0) {
1661 if (className == NULL)
1662 err = PyFile_WriteString("<unknown>", f);
1663 else
1664 err = PyFile_WriteString(className, f);
1665 }
1666 }
1667 if (err == 0 && (value != Py_None)) {
1668 PyObject *s = PyObject_Str(value);
1669 /* only print colon if the str() of the
1670 object is not the empty string
1671 */
1672 if (s == NULL)
1673 err = -1;
1674 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001675 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 err = PyFile_WriteString(": ", f);
1677 if (err == 0)
1678 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1679 Py_XDECREF(s);
1680 }
1681 /* try to write a newline in any case */
1682 err += PyFile_WriteString("\n", f);
1683 Py_XDECREF(tb);
1684 Py_DECREF(value);
1685 /* If an error happened here, don't show it.
1686 XXX This is wrong, but too many callers rely on this behavior. */
1687 if (err != 0)
1688 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001689}
1690
1691static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 "\nThe above exception was the direct cause "
1693 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001694
1695static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 "\nDuring handling of the above exception, "
1697 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001698
1699static void
1700print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 int err = 0, res;
1703 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 if (seen != NULL) {
1706 /* Exception chaining */
1707 if (PySet_Add(seen, value) == -1)
1708 PyErr_Clear();
1709 else if (PyExceptionInstance_Check(value)) {
1710 cause = PyException_GetCause(value);
1711 context = PyException_GetContext(value);
Nick Coghlanab7bf212012-02-26 17:49:52 +10001712 if (cause && cause == Py_None) {
1713 /* print neither cause nor context */
1714 ;
1715 }
1716 else if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 res = PySet_Contains(seen, cause);
1718 if (res == -1)
1719 PyErr_Clear();
1720 if (res == 0) {
1721 print_exception_recursive(
1722 f, cause, seen);
1723 err |= PyFile_WriteString(
1724 cause_message, f);
1725 }
1726 }
1727 else if (context) {
1728 res = PySet_Contains(seen, context);
1729 if (res == -1)
1730 PyErr_Clear();
1731 if (res == 0) {
1732 print_exception_recursive(
1733 f, context, seen);
1734 err |= PyFile_WriteString(
1735 context_message, f);
1736 }
1737 }
1738 Py_XDECREF(context);
1739 Py_XDECREF(cause);
1740 }
1741 }
1742 print_exception(f, value);
1743 if (err != 0)
1744 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001745}
1746
Thomas Wouters477c8d52006-05-27 19:21:47 +00001747void
1748PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 PyObject *seen;
1751 PyObject *f = PySys_GetObject("stderr");
1752 if (f == Py_None) {
1753 /* pass */
1754 }
1755 else if (f == NULL) {
1756 _PyObject_Dump(value);
1757 fprintf(stderr, "lost sys.stderr\n");
1758 }
1759 else {
1760 /* We choose to ignore seen being possibly NULL, and report
1761 at least the main exception (it could be a MemoryError).
1762 */
1763 seen = PySet_New(NULL);
1764 if (seen == NULL)
1765 PyErr_Clear();
1766 print_exception_recursive(f, value, seen);
1767 Py_XDECREF(seen);
1768 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001769}
1770
Guido van Rossum82598051997-03-05 00:20:32 +00001771PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001772PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 PyObject *ret = NULL;
1776 mod_ty mod;
1777 PyArena *arena = PyArena_New();
1778 if (arena == NULL)
1779 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1782 if (mod != NULL)
1783 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1784 PyArena_Free(arena);
1785 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001786}
1787
1788PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001789PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 PyObject *ret;
1793 mod_ty mod;
1794 PyArena *arena = PyArena_New();
1795 if (arena == NULL)
1796 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1799 flags, NULL, arena);
1800 if (closeit)
1801 fclose(fp);
1802 if (mod == NULL) {
1803 PyArena_Free(arena);
1804 return NULL;
1805 }
1806 ret = run_mod(mod, filename, globals, locals, flags, arena);
1807 PyArena_Free(arena);
1808 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001809}
1810
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001811static void
1812flush_io(void)
1813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 PyObject *f, *r;
1815 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001816 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 /* Save the current exception */
1819 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 f = PySys_GetObject("stderr");
1822 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001823 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 if (r)
1825 Py_DECREF(r);
1826 else
1827 PyErr_Clear();
1828 }
1829 f = PySys_GetObject("stdout");
1830 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001831 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 if (r)
1833 Py_DECREF(r);
1834 else
1835 PyErr_Clear();
1836 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001839}
1840
Guido van Rossum82598051997-03-05 00:20:32 +00001841static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 PyCodeObject *co;
1846 PyObject *v;
1847 co = PyAST_Compile(mod, filename, flags, arena);
1848 if (co == NULL)
1849 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001850 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 Py_DECREF(co);
1852 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001853}
1854
Guido van Rossum82598051997-03-05 00:20:32 +00001855static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001856run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 PyCodeObject *co;
1860 PyObject *v;
1861 long magic;
1862 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 magic = PyMarshal_ReadLongFromFile(fp);
1865 if (magic != PyImport_GetMagicNumber()) {
1866 PyErr_SetString(PyExc_RuntimeError,
1867 "Bad magic number in .pyc file");
1868 return NULL;
1869 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001870 /* Skip mtime and size */
1871 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 (void) PyMarshal_ReadLongFromFile(fp);
1873 v = PyMarshal_ReadLastObjectFromFile(fp);
1874 fclose(fp);
1875 if (v == NULL || !PyCode_Check(v)) {
1876 Py_XDECREF(v);
1877 PyErr_SetString(PyExc_RuntimeError,
1878 "Bad code object in .pyc file");
1879 return NULL;
1880 }
1881 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001882 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (v && flags)
1884 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1885 Py_DECREF(co);
1886 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001887}
1888
Guido van Rossum82598051997-03-05 00:20:32 +00001889PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001890Py_CompileStringExFlags(const char *str, const char *filename, int start,
1891 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 PyCodeObject *co;
1894 mod_ty mod;
1895 PyArena *arena = PyArena_New();
1896 if (arena == NULL)
1897 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1900 if (mod == NULL) {
1901 PyArena_Free(arena);
1902 return NULL;
1903 }
1904 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1905 PyObject *result = PyAST_mod2obj(mod);
1906 PyArena_Free(arena);
1907 return result;
1908 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001909 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 PyArena_Free(arena);
1911 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001912}
1913
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001914/* For use in Py_LIMITED_API */
1915#undef Py_CompileString
1916PyObject *
1917PyCompileString(const char *str, const char *filename, int start)
1918{
1919 return Py_CompileStringFlags(str, filename, start, NULL);
1920}
1921
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001922struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001923Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 struct symtable *st;
1926 mod_ty mod;
1927 PyCompilerFlags flags;
1928 PyArena *arena = PyArena_New();
1929 if (arena == NULL)
1930 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 flags.cf_flags = 0;
1933 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1934 if (mod == NULL) {
1935 PyArena_Free(arena);
1936 return NULL;
1937 }
1938 st = PySymtable_Build(mod, filename, 0);
1939 PyArena_Free(arena);
1940 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001941}
1942
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001943/* Preferred access to parser is through AST. */
1944mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001945PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 mod_ty mod;
1949 PyCompilerFlags localflags;
1950 perrdetail err;
1951 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1954 &_PyParser_Grammar, start, &err,
1955 &iflags);
1956 if (flags == NULL) {
1957 localflags.cf_flags = 0;
1958 flags = &localflags;
1959 }
1960 if (n) {
1961 flags->cf_flags |= iflags & PyCF_MASK;
1962 mod = PyAST_FromNode(n, flags, filename, arena);
1963 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 }
1965 else {
1966 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001967 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001969 err_free(&err);
1970 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001971}
1972
1973mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001974PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 int start, char *ps1,
1976 char *ps2, PyCompilerFlags *flags, int *errcode,
1977 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 mod_ty mod;
1980 PyCompilerFlags localflags;
1981 perrdetail err;
1982 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1985 &_PyParser_Grammar,
1986 start, ps1, ps2, &err, &iflags);
1987 if (flags == NULL) {
1988 localflags.cf_flags = 0;
1989 flags = &localflags;
1990 }
1991 if (n) {
1992 flags->cf_flags |= iflags & PyCF_MASK;
1993 mod = PyAST_FromNode(n, flags, filename, arena);
1994 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 }
1996 else {
1997 err_input(&err);
1998 if (errcode)
1999 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002000 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002002 err_free(&err);
2003 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002004}
2005
Guido van Rossuma110aa61994-08-29 12:50:44 +00002006/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002007
Guido van Rossuma110aa61994-08-29 12:50:44 +00002008node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002009PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 perrdetail err;
2012 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2013 &_PyParser_Grammar,
2014 start, NULL, NULL, &err, flags);
2015 if (n == NULL)
2016 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002017 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002020}
2021
Guido van Rossuma110aa61994-08-29 12:50:44 +00002022/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002023
Guido van Rossuma110aa61994-08-29 12:50:44 +00002024node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002025PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 perrdetail err;
2028 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2029 start, &err, flags);
2030 if (n == NULL)
2031 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002032 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002034}
2035
2036node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002037PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 perrdetail err;
2041 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2042 &_PyParser_Grammar, start, &err, flags);
2043 if (n == NULL)
2044 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002045 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002047}
2048
2049node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002050PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002053}
2054
Guido van Rossum66ebd912003-04-17 16:02:26 +00002055/* May want to move a more generalized form of this to parsetok.c or
2056 even parser modules. */
2057
2058void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002059PyParser_ClearError(perrdetail *err)
2060{
2061 err_free(err);
2062}
2063
2064void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002065PyParser_SetError(perrdetail *err)
2066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002068}
2069
Victor Stinner7f2fee32011-04-05 00:39:01 +02002070static void
2071err_free(perrdetail *err)
2072{
2073 Py_CLEAR(err->filename);
2074}
2075
Guido van Rossuma110aa61994-08-29 12:50:44 +00002076/* Set the error appropriate to the given input error code (see errcode.h) */
2077
2078static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002079err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 PyObject *v, *w, *errtype, *errtext;
2082 PyObject *msg_obj = NULL;
2083 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 errtype = PyExc_SyntaxError;
2086 switch (err->error) {
2087 case E_ERROR:
2088 return;
2089 case E_SYNTAX:
2090 errtype = PyExc_IndentationError;
2091 if (err->expected == INDENT)
2092 msg = "expected an indented block";
2093 else if (err->token == INDENT)
2094 msg = "unexpected indent";
2095 else if (err->token == DEDENT)
2096 msg = "unexpected unindent";
2097 else {
2098 errtype = PyExc_SyntaxError;
2099 msg = "invalid syntax";
2100 }
2101 break;
2102 case E_TOKEN:
2103 msg = "invalid token";
2104 break;
2105 case E_EOFS:
2106 msg = "EOF while scanning triple-quoted string literal";
2107 break;
2108 case E_EOLS:
2109 msg = "EOL while scanning string literal";
2110 break;
2111 case E_INTR:
2112 if (!PyErr_Occurred())
2113 PyErr_SetNone(PyExc_KeyboardInterrupt);
2114 goto cleanup;
2115 case E_NOMEM:
2116 PyErr_NoMemory();
2117 goto cleanup;
2118 case E_EOF:
2119 msg = "unexpected EOF while parsing";
2120 break;
2121 case E_TABSPACE:
2122 errtype = PyExc_TabError;
2123 msg = "inconsistent use of tabs and spaces in indentation";
2124 break;
2125 case E_OVERFLOW:
2126 msg = "expression too long";
2127 break;
2128 case E_DEDENT:
2129 errtype = PyExc_IndentationError;
2130 msg = "unindent does not match any outer indentation level";
2131 break;
2132 case E_TOODEEP:
2133 errtype = PyExc_IndentationError;
2134 msg = "too many levels of indentation";
2135 break;
2136 case E_DECODE: {
2137 PyObject *type, *value, *tb;
2138 PyErr_Fetch(&type, &value, &tb);
2139 msg = "unknown decode error";
2140 if (value != NULL)
2141 msg_obj = PyObject_Str(value);
2142 Py_XDECREF(type);
2143 Py_XDECREF(value);
2144 Py_XDECREF(tb);
2145 break;
2146 }
2147 case E_LINECONT:
2148 msg = "unexpected character after line continuation character";
2149 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 case E_IDENTIFIER:
2152 msg = "invalid character in identifier";
2153 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002154 case E_BADSINGLE:
2155 msg = "multiple statements found while compiling a single statement";
2156 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 default:
2158 fprintf(stderr, "error=%d\n", err->error);
2159 msg = "unknown parsing error";
2160 break;
2161 }
2162 /* err->text may not be UTF-8 in case of decoding errors.
2163 Explicitly convert to an object. */
2164 if (!err->text) {
2165 errtext = Py_None;
2166 Py_INCREF(Py_None);
2167 } else {
2168 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2169 "replace");
2170 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002171 v = Py_BuildValue("(OiiN)", err->filename,
2172 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 if (v != NULL) {
2174 if (msg_obj)
2175 w = Py_BuildValue("(OO)", msg_obj, v);
2176 else
2177 w = Py_BuildValue("(sO)", msg, v);
2178 } else
2179 w = NULL;
2180 Py_XDECREF(v);
2181 PyErr_SetObject(errtype, w);
2182 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002183cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 Py_XDECREF(msg_obj);
2185 if (err->text != NULL) {
2186 PyObject_FREE(err->text);
2187 err->text = NULL;
2188 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002189}
2190
2191/* Print fatal error message and abort */
2192
2193void
Tim Peters7c321a82002-07-09 02:57:01 +00002194Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002195{
Victor Stinner024e37a2011-03-31 01:31:06 +02002196 const int fd = fileno(stderr);
2197 PyThreadState *tstate;
2198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 fprintf(stderr, "Fatal Python error: %s\n", msg);
2200 fflush(stderr); /* it helps in Windows debug build */
2201 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002202 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002204 else {
2205 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2206 if (tstate != NULL) {
2207 fputc('\n', stderr);
2208 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002209 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002210 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002211 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002212 }
2213
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002214#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 {
2216 size_t len = strlen(msg);
2217 WCHAR* buffer;
2218 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* Convert the message to wchar_t. This uses a simple one-to-one
2221 conversion, assuming that the this error message actually uses ASCII
2222 only. If this ceases to be true, we will have to convert. */
2223 buffer = alloca( (len+1) * (sizeof *buffer));
2224 for( i=0; i<=len; ++i)
2225 buffer[i] = msg[i];
2226 OutputDebugStringW(L"Fatal Python error: ");
2227 OutputDebugStringW(buffer);
2228 OutputDebugStringW(L"\n");
2229 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002230#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002232#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002233#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002235}
2236
2237/* Clean up and exit */
2238
Guido van Rossuma110aa61994-08-29 12:50:44 +00002239#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002240#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002241#endif
2242
Collin Winter670e6922007-03-21 02:57:17 +00002243static void (*pyexitfunc)(void) = NULL;
2244/* For the atexit module. */
2245void _Py_PyAtExit(void (*func)(void))
2246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002248}
2249
2250static void
2251call_py_exitfuncs(void)
2252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 if (pyexitfunc == NULL)
2254 return;
Collin Winter670e6922007-03-21 02:57:17 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 (*pyexitfunc)();
2257 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002258}
2259
Antoine Pitrou011bd622009-10-20 21:52:47 +00002260/* Wait until threading._shutdown completes, provided
2261 the threading module was imported in the first place.
2262 The shutdown routine will wait until all non-daemon
2263 "threading" threads have completed. */
2264static void
2265wait_for_thread_shutdown(void)
2266{
2267#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002268 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 PyObject *result;
2270 PyThreadState *tstate = PyThreadState_GET();
2271 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2272 "threading");
2273 if (threading == NULL) {
2274 /* threading not imported */
2275 PyErr_Clear();
2276 return;
2277 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002278 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 if (result == NULL) {
2280 PyErr_WriteUnraisable(threading);
2281 }
2282 else {
2283 Py_DECREF(result);
2284 }
2285 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002286#endif
2287}
2288
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002289#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002290static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002291static int nexitfuncs = 0;
2292
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002293int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (nexitfuncs >= NEXITFUNCS)
2296 return -1;
2297 exitfuncs[nexitfuncs++] = func;
2298 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002299}
2300
Guido van Rossumcc283f51997-08-05 02:22:03 +00002301static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002302call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 while (nexitfuncs > 0)
2305 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 fflush(stdout);
2308 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002309}
2310
2311void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002312Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002317}
2318
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002319static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002320initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002321{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002322#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002324#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002325#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002327#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002328#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002330#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002332}
2333
Guido van Rossum7433b121997-02-14 19:45:36 +00002334
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002335/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2336 *
2337 * All of the code in this function must only use async-signal-safe functions,
2338 * listed at `man 7 signal` or
2339 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2340 */
2341void
2342_Py_RestoreSignals(void)
2343{
2344#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002346#endif
2347#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002349#endif
2350#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002352#endif
2353}
2354
2355
Guido van Rossum7433b121997-02-14 19:45:36 +00002356/*
2357 * The file descriptor fd is considered ``interactive'' if either
2358 * a) isatty(fd) is TRUE, or
2359 * b) the -i flag was given, and the filename associated with
2360 * the descriptor is NULL or "<stdin>" or "???".
2361 */
2362int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002363Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 if (isatty((int)fileno(fp)))
2366 return 1;
2367 if (!Py_InteractiveFlag)
2368 return 0;
2369 return (filename == NULL) ||
2370 (strcmp(filename, "<stdin>") == 0) ||
2371 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002372}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002373
2374
Tim Petersd08e3822003-04-17 15:24:21 +00002375#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002376#if defined(WIN32) && defined(_MSC_VER)
2377
2378/* Stack checking for Microsoft C */
2379
2380#include <malloc.h>
2381#include <excpt.h>
2382
Fred Drakee8de31c2000-08-31 05:38:39 +00002383/*
2384 * Return non-zero when we run out of memory on the stack; zero otherwise.
2385 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002386int
Fred Drake399739f2000-08-31 05:52:44 +00002387PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 __try {
2390 /* alloca throws a stack overflow exception if there's
2391 not enough space left on the stack */
2392 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2393 return 0;
2394 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2395 EXCEPTION_EXECUTE_HANDLER :
2396 EXCEPTION_CONTINUE_SEARCH) {
2397 int errcode = _resetstkoflw();
2398 if (errcode == 0)
2399 {
2400 Py_FatalError("Could not reset the stack!");
2401 }
2402 }
2403 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002404}
2405
2406#endif /* WIN32 && _MSC_VER */
2407
2408/* Alternate implementations can be added here... */
2409
2410#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002411
2412
2413/* Wrappers around sigaction() or signal(). */
2414
2415PyOS_sighandler_t
2416PyOS_getsig(int sig)
2417{
2418#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 struct sigaction context;
2420 if (sigaction(sig, NULL, &context) == -1)
2421 return SIG_ERR;
2422 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002423#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002425/* Special signal handling for the secure CRT in Visual Studio 2005 */
2426#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 switch (sig) {
2428 /* Only these signals are valid */
2429 case SIGINT:
2430 case SIGILL:
2431 case SIGFPE:
2432 case SIGSEGV:
2433 case SIGTERM:
2434 case SIGBREAK:
2435 case SIGABRT:
2436 break;
2437 /* Don't call signal() with other values or it will assert */
2438 default:
2439 return SIG_ERR;
2440 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002441#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 handler = signal(sig, SIG_IGN);
2443 if (handler != SIG_ERR)
2444 signal(sig, handler);
2445 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002446#endif
2447}
2448
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002449/*
2450 * All of the code in this function must only use async-signal-safe functions,
2451 * listed at `man 7 signal` or
2452 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2453 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002454PyOS_sighandler_t
2455PyOS_setsig(int sig, PyOS_sighandler_t handler)
2456{
2457#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* Some code in Modules/signalmodule.c depends on sigaction() being
2459 * used here if HAVE_SIGACTION is defined. Fix that if this code
2460 * changes to invalidate that assumption.
2461 */
2462 struct sigaction context, ocontext;
2463 context.sa_handler = handler;
2464 sigemptyset(&context.sa_mask);
2465 context.sa_flags = 0;
2466 if (sigaction(sig, &context, &ocontext) == -1)
2467 return SIG_ERR;
2468 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002469#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 PyOS_sighandler_t oldhandler;
2471 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002472#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002474#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002476#endif
2477}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002478
2479/* Deprecated C API functions still provided for binary compatiblity */
2480
2481#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002482PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002483PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002486}
2487
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002488#undef PyParser_SimpleParseString
2489PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002490PyParser_SimpleParseString(const char *str, int start)
2491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002493}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002494
2495#undef PyRun_AnyFile
2496PyAPI_FUNC(int)
2497PyRun_AnyFile(FILE *fp, const char *name)
2498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002500}
2501
2502#undef PyRun_AnyFileEx
2503PyAPI_FUNC(int)
2504PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002507}
2508
2509#undef PyRun_AnyFileFlags
2510PyAPI_FUNC(int)
2511PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002514}
2515
2516#undef PyRun_File
2517PyAPI_FUNC(PyObject *)
2518PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002521}
2522
2523#undef PyRun_FileEx
2524PyAPI_FUNC(PyObject *)
2525PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002528}
2529
2530#undef PyRun_FileFlags
2531PyAPI_FUNC(PyObject *)
2532PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002536}
2537
2538#undef PyRun_SimpleFile
2539PyAPI_FUNC(int)
2540PyRun_SimpleFile(FILE *f, const char *p)
2541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002543}
2544
2545#undef PyRun_SimpleFileEx
2546PyAPI_FUNC(int)
2547PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002550}
2551
2552
2553#undef PyRun_String
2554PyAPI_FUNC(PyObject *)
2555PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002558}
2559
2560#undef PyRun_SimpleString
2561PyAPI_FUNC(int)
2562PyRun_SimpleString(const char *s)
2563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002565}
2566
2567#undef Py_CompileString
2568PyAPI_FUNC(PyObject *)
2569Py_CompileString(const char *str, const char *p, int s)
2570{
Georg Brandl8334fd92010-12-04 10:26:46 +00002571 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2572}
2573
2574#undef Py_CompileStringFlags
2575PyAPI_FUNC(PyObject *)
2576Py_CompileStringFlags(const char *str, const char *p, int s,
2577 PyCompilerFlags *flags)
2578{
2579 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002580}
2581
2582#undef PyRun_InteractiveOne
2583PyAPI_FUNC(int)
2584PyRun_InteractiveOne(FILE *f, const char *p)
2585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002587}
2588
2589#undef PyRun_InteractiveLoop
2590PyAPI_FUNC(int)
2591PyRun_InteractiveLoop(FILE *f, const char *p)
2592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002594}
2595
2596#ifdef __cplusplus
2597}
2598#endif