blob: 54d39a5a91f37fb84de0317d9cbe60bc2280a00e [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);
Georg Brandl2daf6ae2012-02-20 19:54:16 +010076extern void _PyRandom_Init(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000077
Mark Hammond8d98d2c2003-04-19 15:41:53 +000078#ifdef WITH_THREAD
79extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
80extern void _PyGILState_Fini(void);
81#endif /* WITH_THREAD */
82
Guido van Rossum82598051997-03-05 00:20:32 +000083int Py_DebugFlag; /* Needed by parser.c */
84int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000085int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000086int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020087int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000088int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000089int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000090int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000091int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000092int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000093int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000094int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000095int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +010096int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000097
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020098PyThreadState *_Py_Finalizing = NULL;
99
Christian Heimes33fe8092008-04-13 13:53:33 +0000100/* PyModule_GetWarningsModule is no longer necessary as of 2.6
101since _warnings is builtin. This API should not be used. */
102PyObject *
103PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000106}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000107
Guido van Rossum25ce5661997-08-02 03:10:38 +0000108static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000109
Thomas Wouters7e474022000-07-16 12:04:32 +0000110/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111
112int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000113Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000116}
117
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118/* Global initializations. Can be undone by Py_Finalize(). Don't
119 call this twice without an intervening Py_Finalize() call. When
120 initializations fail, a fatal error is issued and the function does
121 not return. On return, the first thread and interpreter state have
122 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000123
Guido van Rossum25ce5661997-08-02 03:10:38 +0000124 Locking: you must hold the interpreter lock while calling this.
125 (If the lock has not yet been initialized, that's equivalent to
126 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000127
Guido van Rossum25ce5661997-08-02 03:10:38 +0000128*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000129
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000130static int
131add_flag(int flag, const char *envs)
132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 int env = atoi(envs);
134 if (flag < env)
135 flag = env;
136 if (flag < 1)
137 flag = 1;
138 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000139}
140
Christian Heimes5833a2f2008-10-30 21:40:04 +0000141static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000142get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000143{
Victor Stinner94908bb2010-08-18 21:23:25 +0000144 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000145 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200146 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000147
Victor Stinner94908bb2010-08-18 21:23:25 +0000148 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (!codec)
150 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000151
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200152 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 Py_CLEAR(codec);
154 if (!name)
155 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000156
Victor Stinner94908bb2010-08-18 21:23:25 +0000157 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100158 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000159 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000160 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000162 if (name_str == NULL) {
163 PyErr_NoMemory();
164 return NULL;
165 }
166 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000167
168error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000170 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000172}
Victor Stinner94908bb2010-08-18 21:23:25 +0000173
Victor Stinner94908bb2010-08-18 21:23:25 +0000174static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200175get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000176{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200177#ifdef MS_WINDOWS
178 char codepage[100];
179 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
180 return get_codec_name(codepage);
181#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000182 char* codeset = nl_langinfo(CODESET);
183 if (!codeset || codeset[0] == '\0') {
184 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
185 return NULL;
186 }
187 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200188#else
189 PyErr_SetNone(PyExc_NotImplementedError);
190 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000191#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200192}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000193
Guido van Rossuma027efa1997-05-05 20:56:21 +0000194void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000195Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 PyInterpreterState *interp;
198 PyThreadState *tstate;
199 PyObject *bimod, *sysmod, *pstderr;
200 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 if (initialized)
204 return;
205 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200206 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000207
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000208#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 /* Set up the LC_CTYPE locale, so we can obtain
210 the locale's charset without having to switch
211 locales. */
212 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000213#endif
214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
216 Py_DebugFlag = add_flag(Py_DebugFlag, p);
217 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
218 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
219 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
220 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
221 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
222 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100223 /* The variable is only tested for existence here; _PyRandom_Init will
224 check its value further. */
225 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
226 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
227
228 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 interp = PyInterpreterState_New();
231 if (interp == NULL)
232 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 tstate = PyThreadState_New(interp);
235 if (tstate == NULL)
236 Py_FatalError("Py_Initialize: can't make first thread");
237 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000238
Victor Stinner6961bd62010-08-17 22:26:51 +0000239#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000240 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
241 destroying the GIL might fail when it is being referenced from
242 another running thread (see issue #9901).
243 Instead we destroy the previously created GIL here, which ensures
244 that we can call Py_Initialize / Py_Finalize multiple times. */
245 _PyEval_FiniThreads();
246
247 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000248 _PyGILState_Init(interp, tstate);
249#endif /* WITH_THREAD */
250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (!_PyFrame_Init())
254 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 if (!_PyLong_Init())
257 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 if (!PyByteArray_Init())
260 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 interp->modules = PyDict_New();
265 if (interp->modules == NULL)
266 Py_FatalError("Py_Initialize: can't make modules dictionary");
267 interp->modules_reloading = PyDict_New();
268 if (interp->modules_reloading == NULL)
269 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200272 if (_PyUnicode_Init() < 0)
273 Py_FatalError("Py_Initialize: can't initialize unicode");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 bimod = _PyBuiltin_Init();
276 if (bimod == NULL)
277 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000278 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 interp->builtins = PyModule_GetDict(bimod);
280 if (interp->builtins == NULL)
281 Py_FatalError("Py_Initialize: can't initialize builtins dict");
282 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 /* initialize builtin exceptions */
285 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 sysmod = _PySys_Init();
288 if (sysmod == NULL)
289 Py_FatalError("Py_Initialize: can't initialize sys");
290 interp->sysdict = PyModule_GetDict(sysmod);
291 if (interp->sysdict == NULL)
292 Py_FatalError("Py_Initialize: can't initialize sys dict");
293 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000294 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 PySys_SetPath(Py_GetPath());
296 PyDict_SetItemString(interp->sysdict, "modules",
297 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 /* Set up a preliminary stderr printer until we have enough
300 infrastructure for the io module in place. */
301 pstderr = PyFile_NewStdPrinter(fileno(stderr));
302 if (pstderr == NULL)
303 Py_FatalError("Py_Initialize: can't set preliminary stderr");
304 PySys_SetObject("stderr", pstderr);
305 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000306 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000311
Victor Stinner024e37a2011-03-31 01:31:06 +0200312 /* initialize the faulthandler module */
313 if (_PyFaulthandler_Init())
314 Py_FatalError("Py_Initialize: can't initialize faulthandler");
315
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000316 /* Initialize _warnings. */
317 _PyWarnings_Init();
318
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000319 _PyTime_Init();
320
Victor Stinner793b5312011-04-27 00:24:21 +0200321 if (initfsencoding(interp) < 0)
322 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (install_sigs)
325 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 initmain(); /* Module __main__ */
328 if (initstdio() < 0)
329 Py_FatalError(
330 "Py_Initialize: can't initialize sys standard streams");
331
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000332 /* Initialize warnings. */
333 if (PySys_HasWarnOptions()) {
334 PyObject *warnings_module = PyImport_ImportModule("warnings");
335 if (warnings_module == NULL) {
336 fprintf(stderr, "'import warnings' failed; traceback:\n");
337 PyErr_Print();
338 }
339 Py_XDECREF(warnings_module);
340 }
341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (!Py_NoSiteFlag)
343 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000344}
345
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000346void
347Py_Initialize(void)
348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000350}
351
352
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000353#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000354extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000355#endif
356
Guido van Rossume8432ac2007-07-09 15:04:50 +0000357/* Flush stdout and stderr */
358
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100359static int
360file_is_closed(PyObject *fobj)
361{
362 int r;
363 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
364 if (tmp == NULL) {
365 PyErr_Clear();
366 return 0;
367 }
368 r = PyObject_IsTrue(tmp);
369 Py_DECREF(tmp);
370 if (r < 0)
371 PyErr_Clear();
372 return r > 0;
373}
374
Neal Norwitz2bad9702007-08-27 06:19:22 +0000375static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000376flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 PyObject *fout = PySys_GetObject("stdout");
379 PyObject *ferr = PySys_GetObject("stderr");
380 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200381 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000382
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100383 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200384 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000386 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 else
388 Py_DECREF(tmp);
389 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000390
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100391 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200392 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 if (tmp == NULL)
394 PyErr_Clear();
395 else
396 Py_DECREF(tmp);
397 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000398}
399
Guido van Rossum25ce5661997-08-02 03:10:38 +0000400/* Undo the effect of Py_Initialize().
401
402 Beware: if multiple interpreter and/or thread states exist, these
403 are not wiped out; only the current thread and interpreter state
404 are deleted. But since everything else is deleted, those other
405 interpreter and thread states should no longer be used.
406
407 (XXX We should do better, e.g. wipe out all interpreters and
408 threads.)
409
410 Locking: as above.
411
412*/
413
414void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000415Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 PyInterpreterState *interp;
418 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (!initialized)
421 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 /* The interpreter is still entirely intact at this point, and the
426 * exit funcs may be relying on that. In particular, if some thread
427 * or exit func is still waiting to do an import, the import machinery
428 * expects Py_IsInitialized() to return true. So don't say the
429 * interpreter is uninitialized until after the exit funcs have run.
430 * Note that Threading.py uses an exit func to do a join on all the
431 * threads created thru it, so this also protects pending imports in
432 * the threads created via Threading.
433 */
434 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 /* Get current thread state and interpreter pointer */
437 tstate = PyThreadState_GET();
438 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000439
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200440 /* Remaining threads (e.g. daemon threads) will automatically exit
441 after taking the GIL (in PyEval_RestoreThread()). */
442 _Py_Finalizing = tstate;
443 initialized = 0;
444
445 /* Flush stdout+stderr */
446 flush_std_files();
447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 /* Disable signal handling */
449 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 /* Clear type lookup cache */
452 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* Collect garbage. This may call finalizers; it's nice to call these
455 * before all modules are destroyed.
456 * XXX If a __del__ or weakref callback is triggered here, and tries to
457 * XXX import a module, bad things can happen, because Python no
458 * XXX longer believes it's initialized.
459 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
460 * XXX is easy to provoke that way. I've also seen, e.g.,
461 * XXX Exception exceptions.ImportError: 'No module named sha'
462 * XXX in <function callback at 0x008F5718> ignored
463 * XXX but I'm unclear on exactly how that one happens. In any case,
464 * XXX I haven't seen a real-life report of either of these.
465 */
466 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000467#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 /* With COUNT_ALLOCS, it helps to run GC multiple times:
469 each collection might release some types from the type
470 list, so they become garbage. */
471 while (PyGC_Collect() > 0)
472 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000473#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000474 /* We run this while most interpreter state is still alive, so that
475 debug information can be printed out */
476 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* Destroy all modules */
479 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 /* Flush stdout+stderr (again, in case more was printed) */
482 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100485 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 * XXX This is disabled because it caused too many problems. If
487 * XXX a __del__ or weakref callback triggers here, Python code has
488 * XXX a hard time running, because even the sys module has been
489 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
490 * XXX One symptom is a sequence of information-free messages
491 * XXX coming from threads (if a __del__ or callback is invoked,
492 * XXX other threads can execute too, and any exception they encounter
493 * XXX triggers a comedy of errors as subsystem after subsystem
494 * XXX fails to find what it *expects* to find in sys to help report
495 * XXX the exception and consequent unexpected failures). I've also
496 * XXX seen segfaults then, after adding print statements to the
497 * XXX Python code getting called.
498 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000499#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000501#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
504 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000505
Victor Stinner024e37a2011-03-31 01:31:06 +0200506 /* unload faulthandler module */
507 _PyFaulthandler_Fini();
508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000510#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000512#endif
513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000515
Tim Peters9cf25ce2003-04-17 15:21:01 +0000516#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* Display all objects still alive -- this can invoke arbitrary
518 * __repr__ overrides, so requires a mostly-intact interpreter.
519 * Alas, a lot of stuff may still be alive now that will be cleaned
520 * up later.
521 */
522 if (Py_GETENV("PYTHONDUMPREFS"))
523 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000524#endif /* Py_TRACE_REFS */
525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* Clear interpreter state */
527 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 /* Now we decref the exception classes. After this point nothing
530 can raise an exception. That's okay, because each Fini() method
531 below has been checked to make sure no exceptions are ever
532 raised.
533 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000538#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000540#endif /* WITH_THREAD */
541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 /* Delete current thread */
543 PyThreadState_Swap(NULL);
544 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 /* Sundry finalizers */
547 PyMethod_Fini();
548 PyFrame_Fini();
549 PyCFunction_Fini();
550 PyTuple_Fini();
551 PyList_Fini();
552 PySet_Fini();
553 PyBytes_Fini();
554 PyByteArray_Fini();
555 PyLong_Fini();
556 PyFloat_Fini();
557 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100558 PySlice_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 /* Cleanup Unicode implementation */
561 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000564 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 free((char*)Py_FileSystemDefaultEncoding);
566 Py_FileSystemDefaultEncoding = NULL;
567 }
Christian Heimesc8967002007-11-30 10:18:26 +0000568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 /* XXX Still allocated:
570 - various static ad-hoc pointers to interned strings
571 - int and float free list blocks
572 - whatever various modules and libraries allocate
573 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000576
Tim Peters269b2a62003-04-17 19:52:29 +0000577#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* Display addresses (& refcnts) of all objects still alive.
579 * An address can be used to find the repr of the object, printed
580 * above by _Py_PrintReferences.
581 */
582 if (Py_GETENV("PYTHONDUMPREFS"))
583 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000584#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000585#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 if (Py_GETENV("PYTHONMALLOCSTATS"))
587 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000588#endif
589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591}
592
593/* Create and initialize a new interpreter and thread, and return the
594 new thread. This requires that Py_Initialize() has been called
595 first.
596
597 Unsuccessful initialization yields a NULL pointer. Note that *no*
598 exception information is available even in this case -- the
599 exception information is held in the thread, and there is no
600 thread.
601
602 Locking: as above.
603
604*/
605
606PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000607Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyInterpreterState *interp;
610 PyThreadState *tstate, *save_tstate;
611 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 if (!initialized)
614 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 interp = PyInterpreterState_New();
617 if (interp == NULL)
618 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 tstate = PyThreadState_New(interp);
621 if (tstate == NULL) {
622 PyInterpreterState_Delete(interp);
623 return NULL;
624 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 interp->modules = PyDict_New();
631 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000632
Victor Stinner49d3f252010-10-17 01:24:53 +0000633 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (bimod != NULL) {
635 interp->builtins = PyModule_GetDict(bimod);
636 if (interp->builtins == NULL)
637 goto handle_error;
638 Py_INCREF(interp->builtins);
639 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 /* initialize builtin exceptions */
642 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000643
Victor Stinner49d3f252010-10-17 01:24:53 +0000644 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 if (bimod != NULL && sysmod != NULL) {
646 PyObject *pstderr;
647 interp->sysdict = PyModule_GetDict(sysmod);
648 if (interp->sysdict == NULL)
649 goto handle_error;
650 Py_INCREF(interp->sysdict);
651 PySys_SetPath(Py_GetPath());
652 PyDict_SetItemString(interp->sysdict, "modules",
653 interp->modules);
654 /* Set up a preliminary stderr printer until we have enough
655 infrastructure for the io module in place. */
656 pstderr = PyFile_NewStdPrinter(fileno(stderr));
657 if (pstderr == NULL)
658 Py_FatalError("Py_Initialize: can't set preliminary stderr");
659 PySys_SetObject("stderr", pstderr);
660 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000661 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200664
665 if (initfsencoding(interp) < 0)
666 goto handle_error;
667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (initstdio() < 0)
669 Py_FatalError(
670 "Py_Initialize: can't initialize sys standard streams");
671 initmain();
672 if (!Py_NoSiteFlag)
673 initsite();
674 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 if (!PyErr_Occurred())
677 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000678
Thomas Wouters89f507f2006-12-13 04:49:30 +0000679handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000681
Victor Stinnerc40a3502011-04-27 00:20:27 +0200682 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 PyThreadState_Clear(tstate);
684 PyThreadState_Swap(save_tstate);
685 PyThreadState_Delete(tstate);
686 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000689}
690
691/* Delete an interpreter and its last thread. This requires that the
692 given thread state is current, that the thread has no remaining
693 frames, and that it is its interpreter's only remaining thread.
694 It is a fatal error to violate these constraints.
695
696 (Py_Finalize() doesn't have these constraints -- it zaps
697 everything, regardless.)
698
699 Locking: as above.
700
701*/
702
703void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000704Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (tstate != PyThreadState_GET())
709 Py_FatalError("Py_EndInterpreter: thread is not current");
710 if (tstate->frame != NULL)
711 Py_FatalError("Py_EndInterpreter: thread still has a frame");
712 if (tstate != interp->tstate_head || tstate->next != NULL)
713 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyImport_Cleanup();
716 PyInterpreterState_Clear(interp);
717 PyThreadState_Swap(NULL);
718 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000719}
720
Martin v. Löwis790465f2008-04-05 20:41:37 +0000721static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000722
723void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000724Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (pn && *pn)
727 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000728}
729
Martin v. Löwis790465f2008-04-05 20:41:37 +0000730wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000731Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000734}
735
Martin v. Löwis790465f2008-04-05 20:41:37 +0000736static wchar_t *default_home = NULL;
737static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000738
739void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000740Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000743}
744
Martin v. Löwis790465f2008-04-05 20:41:37 +0000745wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000746Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 wchar_t *home = default_home;
749 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
750 char* chome = Py_GETENV("PYTHONHOME");
751 if (chome) {
752 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
753 if (r != (size_t)-1 && r <= PATH_MAX)
754 home = env_home;
755 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 }
758 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000759}
760
Guido van Rossum6135a871995-01-09 17:53:26 +0000761/* Create __main__ module */
762
763static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000764initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyObject *m, *d;
767 m = PyImport_AddModule("__main__");
768 if (m == NULL)
769 Py_FatalError("can't create __main__ module");
770 d = PyModule_GetDict(m);
771 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
772 PyObject *bimod = PyImport_ImportModule("builtins");
773 if (bimod == NULL ||
774 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
775 Py_FatalError("can't add __builtins__ to __main__");
776 Py_DECREF(bimod);
777 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000778}
779
Victor Stinner793b5312011-04-27 00:24:21 +0200780static int
781initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000782{
783 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000784
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200785 if (Py_FileSystemDefaultEncoding == NULL)
786 {
787 Py_FileSystemDefaultEncoding = get_locale_encoding();
788 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000789 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000790
Victor Stinnere4743092010-10-19 00:05:51 +0000791 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200792 interp->fscodec_initialized = 1;
793 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000794 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000795
796 /* the encoding is mbcs, utf-8 or ascii */
797 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
798 if (!codec) {
799 /* Such error can only occurs in critical situations: no more
800 * memory, import a module of the standard library failed,
801 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200802 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000803 }
Victor Stinner793b5312011-04-27 00:24:21 +0200804 Py_DECREF(codec);
805 interp->fscodec_initialized = 1;
806 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000807}
808
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000809/* Import the site module (not into __main__ though) */
810
811static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000812initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PyObject *m;
815 m = PyImport_ImportModule("site");
816 if (m == NULL) {
817 PyErr_Print();
818 Py_Finalize();
819 exit(1);
820 }
821 else {
822 Py_DECREF(m);
823 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000824}
825
Antoine Pitrou05608432009-01-09 18:53:14 +0000826static PyObject*
827create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 int fd, int write_mode, char* name,
829 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
832 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000833 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyObject *line_buffering;
835 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200836 _Py_IDENTIFIER(open);
837 _Py_IDENTIFIER(isatty);
838 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200839 _Py_IDENTIFIER(name);
840 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 /* stdin is always opened in buffered mode, first because it shouldn't
843 make a difference in common use cases, second because TextIOWrapper
844 depends on the presence of a read1() method which only exists on
845 buffered streams.
846 */
847 if (Py_UnbufferedStdioFlag && write_mode)
848 buffering = 0;
849 else
850 buffering = -1;
851 if (write_mode)
852 mode = "wb";
853 else
854 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200855 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
856 fd, mode, buffering,
857 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (buf == NULL)
859 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200862 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200863 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (raw == NULL)
865 goto error;
866 }
867 else {
868 raw = buf;
869 Py_INCREF(raw);
870 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200873 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200875 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 if (res == NULL)
877 goto error;
878 isatty = PyObject_IsTrue(res);
879 Py_DECREF(res);
880 if (isatty == -1)
881 goto error;
882 if (isatty || Py_UnbufferedStdioFlag)
883 line_buffering = Py_True;
884 else
885 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 Py_CLEAR(raw);
888 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000889
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000890 newline = "\n";
891#ifdef MS_WINDOWS
892 if (!write_mode) {
893 /* translate \r\n to \n for sys.stdin on Windows */
894 newline = NULL;
895 }
896#endif
897
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200898 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
899 buf, encoding, errors,
900 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 Py_CLEAR(buf);
902 if (stream == NULL)
903 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 if (write_mode)
906 mode = "w";
907 else
908 mode = "r";
909 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200910 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 goto error;
912 Py_CLEAR(text);
913 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000914
915error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 Py_XDECREF(buf);
917 Py_XDECREF(stream);
918 Py_XDECREF(text);
919 Py_XDECREF(raw);
920 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000921}
922
Antoine Pitrou11942a52011-11-28 19:08:36 +0100923static int
924is_valid_fd(int fd)
925{
926 int dummy_fd;
927 if (fd < 0 || !_PyVerify_fd(fd))
928 return 0;
929 dummy_fd = dup(fd);
930 if (dummy_fd < 0)
931 return 0;
932 close(dummy_fd);
933 return 1;
934}
935
Georg Brandl1a3284e2007-12-02 09:40:06 +0000936/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000937static int
938initstdio(void)
939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyObject *iomod = NULL, *wrapper;
941 PyObject *bimod = NULL;
942 PyObject *m;
943 PyObject *std = NULL;
944 int status = 0, fd;
945 PyObject * encoding_attr;
946 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* Hack to avoid a nasty recursion issue when Python is invoked
949 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
950 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
951 goto error;
952 }
953 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
956 goto error;
957 }
958 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 if (!(bimod = PyImport_ImportModule("builtins"))) {
961 goto error;
962 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (!(iomod = PyImport_ImportModule("io"))) {
965 goto error;
966 }
967 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
968 goto error;
969 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Set builtins.open */
972 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000973 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 goto error;
975 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000976 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 encoding = Py_GETENV("PYTHONIOENCODING");
979 errors = NULL;
980 if (encoding) {
981 encoding = strdup(encoding);
982 errors = strchr(encoding, ':');
983 if (errors) {
984 *errors = '\0';
985 errors++;
986 }
987 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 /* Set sys.stdin */
990 fd = fileno(stdin);
991 /* Under some conditions stdin, stdout and stderr may not be connected
992 * and fileno() may point to an invalid file descriptor. For example
993 * GUI apps don't have valid standard streams by default.
994 */
Antoine Pitrou11942a52011-11-28 19:08:36 +0100995 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 std = Py_None;
997 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 }
999 else {
1000 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1001 if (std == NULL)
1002 goto error;
1003 } /* if (fd < 0) */
1004 PySys_SetObject("__stdin__", std);
1005 PySys_SetObject("stdin", std);
1006 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* Set sys.stdout */
1009 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001010 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 std = Py_None;
1012 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 }
1014 else {
1015 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1016 if (std == NULL)
1017 goto error;
1018 } /* if (fd < 0) */
1019 PySys_SetObject("__stdout__", std);
1020 PySys_SetObject("stdout", std);
1021 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001022
Guido van Rossum98297ee2007-11-06 21:34:58 +00001023#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 /* Set sys.stderr, replaces the preliminary stderr */
1025 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001026 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 std = Py_None;
1028 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 }
1030 else {
1031 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1032 if (std == NULL)
1033 goto error;
1034 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 /* Same as hack above, pre-import stderr's codec to avoid recursion
1037 when import.c tries to write to stderr in verbose mode. */
1038 encoding_attr = PyObject_GetAttrString(std, "encoding");
1039 if (encoding_attr != NULL) {
1040 const char * encoding;
1041 encoding = _PyUnicode_AsString(encoding_attr);
1042 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001043 PyObject *codec_info = _PyCodec_Lookup(encoding);
1044 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001046 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 }
1048 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 PySys_SetObject("__stderr__", std);
1051 PySys_SetObject("stderr", std);
1052 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001053#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001056 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 status = -1;
1058 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 if (encoding)
1061 free(encoding);
1062 Py_XDECREF(bimod);
1063 Py_XDECREF(iomod);
1064 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001065}
1066
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001067/* Parse input from a file and execute it */
1068
1069int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001070PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 if (filename == NULL)
1074 filename = "???";
1075 if (Py_FdIsInteractive(fp, filename)) {
1076 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1077 if (closeit)
1078 fclose(fp);
1079 return err;
1080 }
1081 else
1082 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001083}
1084
1085int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001086PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 PyObject *v;
1089 int ret;
1090 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (flags == NULL) {
1093 flags = &local_flags;
1094 local_flags.cf_flags = 0;
1095 }
1096 v = PySys_GetObject("ps1");
1097 if (v == NULL) {
1098 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1099 Py_XDECREF(v);
1100 }
1101 v = PySys_GetObject("ps2");
1102 if (v == NULL) {
1103 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1104 Py_XDECREF(v);
1105 }
1106 for (;;) {
1107 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1108 PRINT_TOTAL_REFS();
1109 if (ret == E_EOF)
1110 return 0;
1111 /*
1112 if (ret == E_NOMEM)
1113 return -1;
1114 */
1115 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001116}
1117
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001118/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001119static int PARSER_FLAGS(PyCompilerFlags *flags)
1120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 int parser_flags = 0;
1122 if (!flags)
1123 return 0;
1124 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1125 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1126 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1127 parser_flags |= PyPARSE_IGNORE_COOKIE;
1128 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1129 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1130 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001131}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001132
Thomas Wouters89f507f2006-12-13 04:49:30 +00001133#if 0
1134/* Keep an example of flags with future keyword support. */
1135#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1137 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1138 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1139 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001140#endif
1141
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001142int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001143PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *m, *d, *v, *w, *oenc = NULL;
1146 mod_ty mod;
1147 PyArena *arena;
1148 char *ps1 = "", *ps2 = "", *enc = NULL;
1149 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001150 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (fp == stdin) {
1153 /* Fetch encoding from sys.stdin */
1154 v = PySys_GetObject("stdin");
1155 if (v == NULL || v == Py_None)
1156 return -1;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001157 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (!oenc)
1159 return -1;
1160 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001161 if (enc == NULL)
1162 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 }
1164 v = PySys_GetObject("ps1");
1165 if (v != NULL) {
1166 v = PyObject_Str(v);
1167 if (v == NULL)
1168 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001169 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001171 if (ps1 == NULL) {
1172 PyErr_Clear();
1173 ps1 = "";
1174 }
1175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 }
1177 w = PySys_GetObject("ps2");
1178 if (w != NULL) {
1179 w = PyObject_Str(w);
1180 if (w == NULL)
1181 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001182 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001184 if (ps2 == NULL) {
1185 PyErr_Clear();
1186 ps2 = "";
1187 }
1188 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 }
1190 arena = PyArena_New();
1191 if (arena == NULL) {
1192 Py_XDECREF(v);
1193 Py_XDECREF(w);
1194 Py_XDECREF(oenc);
1195 return -1;
1196 }
1197 mod = PyParser_ASTFromFile(fp, filename, enc,
1198 Py_single_input, ps1, ps2,
1199 flags, &errcode, arena);
1200 Py_XDECREF(v);
1201 Py_XDECREF(w);
1202 Py_XDECREF(oenc);
1203 if (mod == NULL) {
1204 PyArena_Free(arena);
1205 if (errcode == E_EOF) {
1206 PyErr_Clear();
1207 return E_EOF;
1208 }
1209 PyErr_Print();
1210 return -1;
1211 }
1212 m = PyImport_AddModule("__main__");
1213 if (m == NULL) {
1214 PyArena_Free(arena);
1215 return -1;
1216 }
1217 d = PyModule_GetDict(m);
1218 v = run_mod(mod, filename, d, d, flags, arena);
1219 PyArena_Free(arena);
1220 flush_io();
1221 if (v == NULL) {
1222 PyErr_Print();
1223 return -1;
1224 }
1225 Py_DECREF(v);
1226 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001227}
1228
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001229/* Check whether a file maybe a pyc file: Look at the extension,
1230 the file type, and, if we may close it, at the first few bytes. */
1231
1232static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001233maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1236 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 /* Only look into the file if we are allowed to close it, since
1239 it then should also be seekable. */
1240 if (closeit) {
1241 /* Read only two bytes of the magic. If the file was opened in
1242 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1243 be read as they are on disk. */
1244 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1245 unsigned char buf[2];
1246 /* Mess: In case of -x, the stream is NOT at its start now,
1247 and ungetc() was used to push back the first newline,
1248 which makes the current stream position formally undefined,
1249 and a x-platform nightmare.
1250 Unfortunately, we have no direct way to know whether -x
1251 was specified. So we use a terrible hack: if the current
1252 stream position is not 0, we assume -x was specified, and
1253 give up. Bug 132850 on SourceForge spells out the
1254 hopelessness of trying anything else (fseek and ftell
1255 don't work predictably x-platform for text-mode files).
1256 */
1257 int ispyc = 0;
1258 if (ftell(fp) == 0) {
1259 if (fread(buf, 1, 2, fp) == 2 &&
1260 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1261 ispyc = 1;
1262 rewind(fp);
1263 }
1264 return ispyc;
1265 }
1266 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001267}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001268
Guido van Rossum0df002c2000-08-27 19:21:52 +00001269int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001270PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 PyObject *m, *d, *v;
1274 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001275 int set_file_name = 0, ret;
1276 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 m = PyImport_AddModule("__main__");
1279 if (m == NULL)
1280 return -1;
1281 d = PyModule_GetDict(m);
1282 if (PyDict_GetItemString(d, "__file__") == NULL) {
1283 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001284 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (f == NULL)
1286 return -1;
1287 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1288 Py_DECREF(f);
1289 return -1;
1290 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001291 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1292 Py_DECREF(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 return -1;
Barry Warsaw916048d2011-09-20 14:45:44 -04001294 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 set_file_name = 1;
1296 Py_DECREF(f);
1297 }
1298 len = strlen(filename);
1299 ext = filename + len - (len > 4 ? 4 : 0);
1300 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1301 /* Try to run a pyc file. First, re-open in binary */
1302 if (closeit)
1303 fclose(fp);
1304 if ((fp = fopen(filename, "rb")) == NULL) {
1305 fprintf(stderr, "python: Can't reopen .pyc file\n");
1306 ret = -1;
1307 goto done;
1308 }
1309 /* Turn on optimization if a .pyo file is given */
1310 if (strcmp(ext, ".pyo") == 0)
1311 Py_OptimizeFlag = 1;
1312 v = run_pyc_file(fp, filename, d, d, flags);
1313 } else {
1314 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1315 closeit, flags);
1316 }
1317 flush_io();
1318 if (v == NULL) {
1319 PyErr_Print();
1320 ret = -1;
1321 goto done;
1322 }
1323 Py_DECREF(v);
1324 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001325 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1327 PyErr_Clear();
1328 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001329}
1330
1331int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001332PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 PyObject *m, *d, *v;
1335 m = PyImport_AddModule("__main__");
1336 if (m == NULL)
1337 return -1;
1338 d = PyModule_GetDict(m);
1339 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1340 if (v == NULL) {
1341 PyErr_Print();
1342 return -1;
1343 }
1344 Py_DECREF(v);
1345 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001346}
1347
Barry Warsaw035574d1997-08-29 22:07:17 +00001348static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001349parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 long hold;
1353 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001354 _Py_IDENTIFIER(msg);
1355 _Py_IDENTIFIER(filename);
1356 _Py_IDENTIFIER(lineno);
1357 _Py_IDENTIFIER(offset);
1358 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001361
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001362 if (! (v = _PyObject_GetAttrId(err, &PyId_msg)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 goto finally;
1364 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001365
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001366 if (!(v = _PyObject_GetAttrId(err, &PyId_filename)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 goto finally;
1368 if (v == Py_None)
1369 *filename = NULL;
1370 else if (! (*filename = _PyUnicode_AsString(v)))
1371 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 Py_DECREF(v);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001374 if (!(v = _PyObject_GetAttrId(err, &PyId_lineno)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 goto finally;
1376 hold = PyLong_AsLong(v);
1377 Py_DECREF(v);
1378 v = NULL;
1379 if (hold < 0 && PyErr_Occurred())
1380 goto finally;
1381 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001382
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001383 if (!(v = _PyObject_GetAttrId(err, &PyId_offset)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 goto finally;
1385 if (v == Py_None) {
1386 *offset = -1;
1387 Py_DECREF(v);
1388 v = NULL;
1389 } else {
1390 hold = PyLong_AsLong(v);
1391 Py_DECREF(v);
1392 v = NULL;
1393 if (hold < 0 && PyErr_Occurred())
1394 goto finally;
1395 *offset = (int)hold;
1396 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001397
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001398 if (!(v = _PyObject_GetAttrId(err, &PyId_text)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 goto finally;
1400 if (v == Py_None)
1401 *text = NULL;
1402 else if (!PyUnicode_Check(v) ||
1403 !(*text = _PyUnicode_AsString(v)))
1404 goto finally;
1405 Py_DECREF(v);
1406 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001407
1408finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 Py_XDECREF(v);
1410 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001411}
1412
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001413void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001414PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001417}
1418
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001419static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001420print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 char *nl;
1423 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001424 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1425 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 for (;;) {
1427 nl = strchr(text, '\n');
1428 if (nl == NULL || nl-text >= offset)
1429 break;
1430 offset -= (int)(nl+1-text);
1431 text = nl+1;
1432 }
1433 while (*text == ' ' || *text == '\t') {
1434 text++;
1435 offset--;
1436 }
1437 }
1438 PyFile_WriteString(" ", f);
1439 PyFile_WriteString(text, f);
1440 if (*text == '\0' || text[strlen(text)-1] != '\n')
1441 PyFile_WriteString("\n", f);
1442 if (offset == -1)
1443 return;
1444 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001445 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001448}
1449
Guido van Rossum66e8e862001-03-23 17:54:43 +00001450static void
1451handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyObject *exception, *value, *tb;
1454 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 if (Py_InspectFlag)
1457 /* Don't exit if -i flag was given. This flag is set to 0
1458 * when entering interactive mode for inspecting. */
1459 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 PyErr_Fetch(&exception, &value, &tb);
1462 fflush(stdout);
1463 if (value == NULL || value == Py_None)
1464 goto done;
1465 if (PyExceptionInstance_Check(value)) {
1466 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001467 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001468 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (code) {
1470 Py_DECREF(value);
1471 value = code;
1472 if (value == Py_None)
1473 goto done;
1474 }
1475 /* If we failed to dig out the 'code' attribute,
1476 just let the else clause below print the error. */
1477 }
1478 if (PyLong_Check(value))
1479 exitcode = (int)PyLong_AsLong(value);
1480 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001481 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001482 if (sys_stderr != NULL && sys_stderr != Py_None) {
1483 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1484 } else {
1485 PyObject_Print(value, stderr, Py_PRINT_RAW);
1486 fflush(stderr);
1487 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 PySys_WriteStderr("\n");
1489 exitcode = 1;
1490 }
Tim Peterscf615b52003-04-19 18:47:02 +00001491 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 /* Restore and clear the exception info, in order to properly decref
1493 * the exception, value, and traceback. If we just exit instead,
1494 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1495 * some finalizers from running.
1496 */
1497 PyErr_Restore(exception, value, tb);
1498 PyErr_Clear();
1499 Py_Exit(exitcode);
1500 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001501}
1502
1503void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001504PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1509 handle_system_exit();
1510 }
1511 PyErr_Fetch(&exception, &v, &tb);
1512 if (exception == NULL)
1513 return;
1514 PyErr_NormalizeException(&exception, &v, &tb);
1515 if (tb == NULL) {
1516 tb = Py_None;
1517 Py_INCREF(tb);
1518 }
1519 PyException_SetTraceback(v, tb);
1520 if (exception == NULL)
1521 return;
1522 /* Now we know v != NULL too */
1523 if (set_sys_last_vars) {
1524 PySys_SetObject("last_type", exception);
1525 PySys_SetObject("last_value", v);
1526 PySys_SetObject("last_traceback", tb);
1527 }
1528 hook = PySys_GetObject("excepthook");
1529 if (hook) {
1530 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1531 PyObject *result = PyEval_CallObject(hook, args);
1532 if (result == NULL) {
1533 PyObject *exception2, *v2, *tb2;
1534 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1535 handle_system_exit();
1536 }
1537 PyErr_Fetch(&exception2, &v2, &tb2);
1538 PyErr_NormalizeException(&exception2, &v2, &tb2);
1539 /* It should not be possible for exception2 or v2
1540 to be NULL. However PyErr_Display() can't
1541 tolerate NULLs, so just be safe. */
1542 if (exception2 == NULL) {
1543 exception2 = Py_None;
1544 Py_INCREF(exception2);
1545 }
1546 if (v2 == NULL) {
1547 v2 = Py_None;
1548 Py_INCREF(v2);
1549 }
1550 fflush(stdout);
1551 PySys_WriteStderr("Error in sys.excepthook:\n");
1552 PyErr_Display(exception2, v2, tb2);
1553 PySys_WriteStderr("\nOriginal exception was:\n");
1554 PyErr_Display(exception, v, tb);
1555 Py_DECREF(exception2);
1556 Py_DECREF(v2);
1557 Py_XDECREF(tb2);
1558 }
1559 Py_XDECREF(result);
1560 Py_XDECREF(args);
1561 } else {
1562 PySys_WriteStderr("sys.excepthook is missing\n");
1563 PyErr_Display(exception, v, tb);
1564 }
1565 Py_XDECREF(exception);
1566 Py_XDECREF(v);
1567 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001568}
1569
Benjamin Petersone6528212008-07-15 15:32:09 +00001570static void
1571print_exception(PyObject *f, PyObject *value)
1572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 int err = 0;
1574 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001575 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 if (!PyExceptionInstance_Check(value)) {
1578 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1579 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1580 PyFile_WriteString(" found\n", f);
1581 return;
1582 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 Py_INCREF(value);
1585 fflush(stdout);
1586 type = (PyObject *) Py_TYPE(value);
1587 tb = PyException_GetTraceback(value);
1588 if (tb && tb != Py_None)
1589 err = PyTraceBack_Print(tb, f);
1590 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001591 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 {
1593 PyObject *message;
1594 const char *filename, *text;
1595 int lineno, offset;
1596 if (!parse_syntax_error(value, &message, &filename,
1597 &lineno, &offset, &text))
1598 PyErr_Clear();
1599 else {
1600 char buf[10];
1601 PyFile_WriteString(" File \"", f);
1602 if (filename == NULL)
1603 PyFile_WriteString("<string>", f);
1604 else
1605 PyFile_WriteString(filename, f);
1606 PyFile_WriteString("\", line ", f);
1607 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1608 PyFile_WriteString(buf, f);
1609 PyFile_WriteString("\n", f);
1610 if (text != NULL)
1611 print_error_text(f, offset, text);
1612 Py_DECREF(value);
1613 value = message;
1614 /* Can't be bothered to check all those
1615 PyFile_WriteString() calls */
1616 if (PyErr_Occurred())
1617 err = -1;
1618 }
1619 }
1620 if (err) {
1621 /* Don't do anything else */
1622 }
1623 else {
1624 PyObject* moduleName;
1625 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001626 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 assert(PyExceptionClass_Check(type));
1628 className = PyExceptionClass_Name(type);
1629 if (className != NULL) {
1630 char *dot = strrchr(className, '.');
1631 if (dot != NULL)
1632 className = dot+1;
1633 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001634
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001635 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1637 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001638 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 err = PyFile_WriteString("<unknown>", f);
1640 }
1641 else {
1642 char* modstr = _PyUnicode_AsString(moduleName);
1643 if (modstr && strcmp(modstr, "builtins"))
1644 {
1645 err = PyFile_WriteString(modstr, f);
1646 err += PyFile_WriteString(".", f);
1647 }
1648 Py_DECREF(moduleName);
1649 }
1650 if (err == 0) {
1651 if (className == NULL)
1652 err = PyFile_WriteString("<unknown>", f);
1653 else
1654 err = PyFile_WriteString(className, f);
1655 }
1656 }
1657 if (err == 0 && (value != Py_None)) {
1658 PyObject *s = PyObject_Str(value);
1659 /* only print colon if the str() of the
1660 object is not the empty string
1661 */
1662 if (s == NULL)
1663 err = -1;
1664 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001665 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 err = PyFile_WriteString(": ", f);
1667 if (err == 0)
1668 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1669 Py_XDECREF(s);
1670 }
1671 /* try to write a newline in any case */
1672 err += PyFile_WriteString("\n", f);
1673 Py_XDECREF(tb);
1674 Py_DECREF(value);
1675 /* If an error happened here, don't show it.
1676 XXX This is wrong, but too many callers rely on this behavior. */
1677 if (err != 0)
1678 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001679}
1680
1681static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 "\nThe above exception was the direct cause "
1683 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001684
1685static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 "\nDuring handling of the above exception, "
1687 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001688
1689static void
1690print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 int err = 0, res;
1693 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 if (seen != NULL) {
1696 /* Exception chaining */
1697 if (PySet_Add(seen, value) == -1)
1698 PyErr_Clear();
1699 else if (PyExceptionInstance_Check(value)) {
1700 cause = PyException_GetCause(value);
1701 context = PyException_GetContext(value);
1702 if (cause) {
1703 res = PySet_Contains(seen, cause);
1704 if (res == -1)
1705 PyErr_Clear();
1706 if (res == 0) {
1707 print_exception_recursive(
1708 f, cause, seen);
1709 err |= PyFile_WriteString(
1710 cause_message, f);
1711 }
1712 }
1713 else if (context) {
1714 res = PySet_Contains(seen, context);
1715 if (res == -1)
1716 PyErr_Clear();
1717 if (res == 0) {
1718 print_exception_recursive(
1719 f, context, seen);
1720 err |= PyFile_WriteString(
1721 context_message, f);
1722 }
1723 }
1724 Py_XDECREF(context);
1725 Py_XDECREF(cause);
1726 }
1727 }
1728 print_exception(f, value);
1729 if (err != 0)
1730 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001731}
1732
Thomas Wouters477c8d52006-05-27 19:21:47 +00001733void
1734PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyObject *seen;
1737 PyObject *f = PySys_GetObject("stderr");
1738 if (f == Py_None) {
1739 /* pass */
1740 }
1741 else if (f == NULL) {
1742 _PyObject_Dump(value);
1743 fprintf(stderr, "lost sys.stderr\n");
1744 }
1745 else {
1746 /* We choose to ignore seen being possibly NULL, and report
1747 at least the main exception (it could be a MemoryError).
1748 */
1749 seen = PySet_New(NULL);
1750 if (seen == NULL)
1751 PyErr_Clear();
1752 print_exception_recursive(f, value, seen);
1753 Py_XDECREF(seen);
1754 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001755}
1756
Guido van Rossum82598051997-03-05 00:20:32 +00001757PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001758PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 PyObject *ret = NULL;
1762 mod_ty mod;
1763 PyArena *arena = PyArena_New();
1764 if (arena == NULL)
1765 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1768 if (mod != NULL)
1769 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1770 PyArena_Free(arena);
1771 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001772}
1773
1774PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001775PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 PyObject *ret;
1779 mod_ty mod;
1780 PyArena *arena = PyArena_New();
1781 if (arena == NULL)
1782 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1785 flags, NULL, arena);
1786 if (closeit)
1787 fclose(fp);
1788 if (mod == NULL) {
1789 PyArena_Free(arena);
1790 return NULL;
1791 }
1792 ret = run_mod(mod, filename, globals, locals, flags, arena);
1793 PyArena_Free(arena);
1794 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001795}
1796
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001797static void
1798flush_io(void)
1799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 PyObject *f, *r;
1801 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001802 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /* Save the current exception */
1805 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 f = PySys_GetObject("stderr");
1808 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001809 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 if (r)
1811 Py_DECREF(r);
1812 else
1813 PyErr_Clear();
1814 }
1815 f = PySys_GetObject("stdout");
1816 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001817 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (r)
1819 Py_DECREF(r);
1820 else
1821 PyErr_Clear();
1822 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001825}
1826
Guido van Rossum82598051997-03-05 00:20:32 +00001827static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 PyCodeObject *co;
1832 PyObject *v;
1833 co = PyAST_Compile(mod, filename, flags, arena);
1834 if (co == NULL)
1835 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001836 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 Py_DECREF(co);
1838 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001839}
1840
Guido van Rossum82598051997-03-05 00:20:32 +00001841static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001842run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 PyCodeObject *co;
1846 PyObject *v;
1847 long magic;
1848 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 magic = PyMarshal_ReadLongFromFile(fp);
1851 if (magic != PyImport_GetMagicNumber()) {
1852 PyErr_SetString(PyExc_RuntimeError,
1853 "Bad magic number in .pyc file");
1854 return NULL;
1855 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001856 /* Skip mtime and size */
1857 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 (void) PyMarshal_ReadLongFromFile(fp);
1859 v = PyMarshal_ReadLastObjectFromFile(fp);
1860 fclose(fp);
1861 if (v == NULL || !PyCode_Check(v)) {
1862 Py_XDECREF(v);
1863 PyErr_SetString(PyExc_RuntimeError,
1864 "Bad code object in .pyc file");
1865 return NULL;
1866 }
1867 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001868 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 if (v && flags)
1870 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1871 Py_DECREF(co);
1872 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001873}
1874
Guido van Rossum82598051997-03-05 00:20:32 +00001875PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001876Py_CompileStringExFlags(const char *str, const char *filename, int start,
1877 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 PyCodeObject *co;
1880 mod_ty mod;
1881 PyArena *arena = PyArena_New();
1882 if (arena == NULL)
1883 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1886 if (mod == NULL) {
1887 PyArena_Free(arena);
1888 return NULL;
1889 }
1890 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1891 PyObject *result = PyAST_mod2obj(mod);
1892 PyArena_Free(arena);
1893 return result;
1894 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001895 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 PyArena_Free(arena);
1897 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001898}
1899
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001900/* For use in Py_LIMITED_API */
1901#undef Py_CompileString
1902PyObject *
1903PyCompileString(const char *str, const char *filename, int start)
1904{
1905 return Py_CompileStringFlags(str, filename, start, NULL);
1906}
1907
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001908struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001909Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 struct symtable *st;
1912 mod_ty mod;
1913 PyCompilerFlags flags;
1914 PyArena *arena = PyArena_New();
1915 if (arena == NULL)
1916 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 flags.cf_flags = 0;
1919 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1920 if (mod == NULL) {
1921 PyArena_Free(arena);
1922 return NULL;
1923 }
1924 st = PySymtable_Build(mod, filename, 0);
1925 PyArena_Free(arena);
1926 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001927}
1928
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001929/* Preferred access to parser is through AST. */
1930mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001931PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 mod_ty mod;
1935 PyCompilerFlags localflags;
1936 perrdetail err;
1937 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1940 &_PyParser_Grammar, start, &err,
1941 &iflags);
1942 if (flags == NULL) {
1943 localflags.cf_flags = 0;
1944 flags = &localflags;
1945 }
1946 if (n) {
1947 flags->cf_flags |= iflags & PyCF_MASK;
1948 mod = PyAST_FromNode(n, flags, filename, arena);
1949 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 }
1951 else {
1952 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001953 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001955 err_free(&err);
1956 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001957}
1958
1959mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001960PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 int start, char *ps1,
1962 char *ps2, PyCompilerFlags *flags, int *errcode,
1963 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001964{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 mod_ty mod;
1966 PyCompilerFlags localflags;
1967 perrdetail err;
1968 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1971 &_PyParser_Grammar,
1972 start, ps1, ps2, &err, &iflags);
1973 if (flags == NULL) {
1974 localflags.cf_flags = 0;
1975 flags = &localflags;
1976 }
1977 if (n) {
1978 flags->cf_flags |= iflags & PyCF_MASK;
1979 mod = PyAST_FromNode(n, flags, filename, arena);
1980 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 }
1982 else {
1983 err_input(&err);
1984 if (errcode)
1985 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02001986 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001988 err_free(&err);
1989 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001990}
1991
Guido van Rossuma110aa61994-08-29 12:50:44 +00001992/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001993
Guido van Rossuma110aa61994-08-29 12:50:44 +00001994node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001995PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 perrdetail err;
1998 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1999 &_PyParser_Grammar,
2000 start, NULL, NULL, &err, flags);
2001 if (n == NULL)
2002 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002003 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002006}
2007
Guido van Rossuma110aa61994-08-29 12:50:44 +00002008/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002009
Guido van Rossuma110aa61994-08-29 12:50:44 +00002010node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002011PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 perrdetail err;
2014 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2015 start, &err, flags);
2016 if (n == NULL)
2017 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002018 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002020}
2021
2022node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002023PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 perrdetail err;
2027 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2028 &_PyParser_Grammar, start, &err, flags);
2029 if (n == NULL)
2030 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002031 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002033}
2034
2035node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002036PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002039}
2040
Guido van Rossum66ebd912003-04-17 16:02:26 +00002041/* May want to move a more generalized form of this to parsetok.c or
2042 even parser modules. */
2043
2044void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002045PyParser_ClearError(perrdetail *err)
2046{
2047 err_free(err);
2048}
2049
2050void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002051PyParser_SetError(perrdetail *err)
2052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002054}
2055
Victor Stinner7f2fee32011-04-05 00:39:01 +02002056static void
2057err_free(perrdetail *err)
2058{
2059 Py_CLEAR(err->filename);
2060}
2061
Guido van Rossuma110aa61994-08-29 12:50:44 +00002062/* Set the error appropriate to the given input error code (see errcode.h) */
2063
2064static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002065err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyObject *v, *w, *errtype, *errtext;
2068 PyObject *msg_obj = NULL;
2069 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 errtype = PyExc_SyntaxError;
2072 switch (err->error) {
2073 case E_ERROR:
2074 return;
2075 case E_SYNTAX:
2076 errtype = PyExc_IndentationError;
2077 if (err->expected == INDENT)
2078 msg = "expected an indented block";
2079 else if (err->token == INDENT)
2080 msg = "unexpected indent";
2081 else if (err->token == DEDENT)
2082 msg = "unexpected unindent";
2083 else {
2084 errtype = PyExc_SyntaxError;
2085 msg = "invalid syntax";
2086 }
2087 break;
2088 case E_TOKEN:
2089 msg = "invalid token";
2090 break;
2091 case E_EOFS:
2092 msg = "EOF while scanning triple-quoted string literal";
2093 break;
2094 case E_EOLS:
2095 msg = "EOL while scanning string literal";
2096 break;
2097 case E_INTR:
2098 if (!PyErr_Occurred())
2099 PyErr_SetNone(PyExc_KeyboardInterrupt);
2100 goto cleanup;
2101 case E_NOMEM:
2102 PyErr_NoMemory();
2103 goto cleanup;
2104 case E_EOF:
2105 msg = "unexpected EOF while parsing";
2106 break;
2107 case E_TABSPACE:
2108 errtype = PyExc_TabError;
2109 msg = "inconsistent use of tabs and spaces in indentation";
2110 break;
2111 case E_OVERFLOW:
2112 msg = "expression too long";
2113 break;
2114 case E_DEDENT:
2115 errtype = PyExc_IndentationError;
2116 msg = "unindent does not match any outer indentation level";
2117 break;
2118 case E_TOODEEP:
2119 errtype = PyExc_IndentationError;
2120 msg = "too many levels of indentation";
2121 break;
2122 case E_DECODE: {
2123 PyObject *type, *value, *tb;
2124 PyErr_Fetch(&type, &value, &tb);
2125 msg = "unknown decode error";
2126 if (value != NULL)
2127 msg_obj = PyObject_Str(value);
2128 Py_XDECREF(type);
2129 Py_XDECREF(value);
2130 Py_XDECREF(tb);
2131 break;
2132 }
2133 case E_LINECONT:
2134 msg = "unexpected character after line continuation character";
2135 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 case E_IDENTIFIER:
2138 msg = "invalid character in identifier";
2139 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002140 case E_BADSINGLE:
2141 msg = "multiple statements found while compiling a single statement";
2142 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 default:
2144 fprintf(stderr, "error=%d\n", err->error);
2145 msg = "unknown parsing error";
2146 break;
2147 }
2148 /* err->text may not be UTF-8 in case of decoding errors.
2149 Explicitly convert to an object. */
2150 if (!err->text) {
2151 errtext = Py_None;
2152 Py_INCREF(Py_None);
2153 } else {
2154 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2155 "replace");
2156 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002157 v = Py_BuildValue("(OiiN)", err->filename,
2158 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 if (v != NULL) {
2160 if (msg_obj)
2161 w = Py_BuildValue("(OO)", msg_obj, v);
2162 else
2163 w = Py_BuildValue("(sO)", msg, v);
2164 } else
2165 w = NULL;
2166 Py_XDECREF(v);
2167 PyErr_SetObject(errtype, w);
2168 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002169cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 Py_XDECREF(msg_obj);
2171 if (err->text != NULL) {
2172 PyObject_FREE(err->text);
2173 err->text = NULL;
2174 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002175}
2176
2177/* Print fatal error message and abort */
2178
2179void
Tim Peters7c321a82002-07-09 02:57:01 +00002180Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002181{
Victor Stinner024e37a2011-03-31 01:31:06 +02002182 const int fd = fileno(stderr);
2183 PyThreadState *tstate;
2184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 fprintf(stderr, "Fatal Python error: %s\n", msg);
2186 fflush(stderr); /* it helps in Windows debug build */
2187 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002188 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002190 else {
2191 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2192 if (tstate != NULL) {
2193 fputc('\n', stderr);
2194 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002195 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002196 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002197 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002198 }
2199
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002200#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 {
2202 size_t len = strlen(msg);
2203 WCHAR* buffer;
2204 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 /* Convert the message to wchar_t. This uses a simple one-to-one
2207 conversion, assuming that the this error message actually uses ASCII
2208 only. If this ceases to be true, we will have to convert. */
2209 buffer = alloca( (len+1) * (sizeof *buffer));
2210 for( i=0; i<=len; ++i)
2211 buffer[i] = msg[i];
2212 OutputDebugStringW(L"Fatal Python error: ");
2213 OutputDebugStringW(buffer);
2214 OutputDebugStringW(L"\n");
2215 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002216#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002218#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002219#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002221}
2222
2223/* Clean up and exit */
2224
Guido van Rossuma110aa61994-08-29 12:50:44 +00002225#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002226#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002227#endif
2228
Collin Winter670e6922007-03-21 02:57:17 +00002229static void (*pyexitfunc)(void) = NULL;
2230/* For the atexit module. */
2231void _Py_PyAtExit(void (*func)(void))
2232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002234}
2235
2236static void
2237call_py_exitfuncs(void)
2238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 if (pyexitfunc == NULL)
2240 return;
Collin Winter670e6922007-03-21 02:57:17 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 (*pyexitfunc)();
2243 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002244}
2245
Antoine Pitrou011bd622009-10-20 21:52:47 +00002246/* Wait until threading._shutdown completes, provided
2247 the threading module was imported in the first place.
2248 The shutdown routine will wait until all non-daemon
2249 "threading" threads have completed. */
2250static void
2251wait_for_thread_shutdown(void)
2252{
2253#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002254 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 PyObject *result;
2256 PyThreadState *tstate = PyThreadState_GET();
2257 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2258 "threading");
2259 if (threading == NULL) {
2260 /* threading not imported */
2261 PyErr_Clear();
2262 return;
2263 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002264 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (result == NULL) {
2266 PyErr_WriteUnraisable(threading);
2267 }
2268 else {
2269 Py_DECREF(result);
2270 }
2271 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002272#endif
2273}
2274
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002275#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002276static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002277static int nexitfuncs = 0;
2278
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002279int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 if (nexitfuncs >= NEXITFUNCS)
2282 return -1;
2283 exitfuncs[nexitfuncs++] = func;
2284 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002285}
2286
Guido van Rossumcc283f51997-08-05 02:22:03 +00002287static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002288call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 while (nexitfuncs > 0)
2291 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 fflush(stdout);
2294 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002295}
2296
2297void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002298Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002303}
2304
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002305static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002306initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002307{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002308#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002310#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002311#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002313#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002314#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002316#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002318}
2319
Guido van Rossum7433b121997-02-14 19:45:36 +00002320
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002321/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2322 *
2323 * All of the code in this function must only use async-signal-safe functions,
2324 * listed at `man 7 signal` or
2325 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2326 */
2327void
2328_Py_RestoreSignals(void)
2329{
2330#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002332#endif
2333#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002335#endif
2336#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002338#endif
2339}
2340
2341
Guido van Rossum7433b121997-02-14 19:45:36 +00002342/*
2343 * The file descriptor fd is considered ``interactive'' if either
2344 * a) isatty(fd) is TRUE, or
2345 * b) the -i flag was given, and the filename associated with
2346 * the descriptor is NULL or "<stdin>" or "???".
2347 */
2348int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002349Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 if (isatty((int)fileno(fp)))
2352 return 1;
2353 if (!Py_InteractiveFlag)
2354 return 0;
2355 return (filename == NULL) ||
2356 (strcmp(filename, "<stdin>") == 0) ||
2357 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002358}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002359
2360
Tim Petersd08e3822003-04-17 15:24:21 +00002361#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002362#if defined(WIN32) && defined(_MSC_VER)
2363
2364/* Stack checking for Microsoft C */
2365
2366#include <malloc.h>
2367#include <excpt.h>
2368
Fred Drakee8de31c2000-08-31 05:38:39 +00002369/*
2370 * Return non-zero when we run out of memory on the stack; zero otherwise.
2371 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002372int
Fred Drake399739f2000-08-31 05:52:44 +00002373PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 __try {
2376 /* alloca throws a stack overflow exception if there's
2377 not enough space left on the stack */
2378 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2379 return 0;
2380 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2381 EXCEPTION_EXECUTE_HANDLER :
2382 EXCEPTION_CONTINUE_SEARCH) {
2383 int errcode = _resetstkoflw();
2384 if (errcode == 0)
2385 {
2386 Py_FatalError("Could not reset the stack!");
2387 }
2388 }
2389 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002390}
2391
2392#endif /* WIN32 && _MSC_VER */
2393
2394/* Alternate implementations can be added here... */
2395
2396#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002397
2398
2399/* Wrappers around sigaction() or signal(). */
2400
2401PyOS_sighandler_t
2402PyOS_getsig(int sig)
2403{
2404#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 struct sigaction context;
2406 if (sigaction(sig, NULL, &context) == -1)
2407 return SIG_ERR;
2408 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002409#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002411/* Special signal handling for the secure CRT in Visual Studio 2005 */
2412#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 switch (sig) {
2414 /* Only these signals are valid */
2415 case SIGINT:
2416 case SIGILL:
2417 case SIGFPE:
2418 case SIGSEGV:
2419 case SIGTERM:
2420 case SIGBREAK:
2421 case SIGABRT:
2422 break;
2423 /* Don't call signal() with other values or it will assert */
2424 default:
2425 return SIG_ERR;
2426 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002427#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 handler = signal(sig, SIG_IGN);
2429 if (handler != SIG_ERR)
2430 signal(sig, handler);
2431 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002432#endif
2433}
2434
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002435/*
2436 * All of the code in this function must only use async-signal-safe functions,
2437 * listed at `man 7 signal` or
2438 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2439 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002440PyOS_sighandler_t
2441PyOS_setsig(int sig, PyOS_sighandler_t handler)
2442{
2443#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 /* Some code in Modules/signalmodule.c depends on sigaction() being
2445 * used here if HAVE_SIGACTION is defined. Fix that if this code
2446 * changes to invalidate that assumption.
2447 */
2448 struct sigaction context, ocontext;
2449 context.sa_handler = handler;
2450 sigemptyset(&context.sa_mask);
2451 context.sa_flags = 0;
2452 if (sigaction(sig, &context, &ocontext) == -1)
2453 return SIG_ERR;
2454 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002455#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 PyOS_sighandler_t oldhandler;
2457 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002458#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002460#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002462#endif
2463}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464
2465/* Deprecated C API functions still provided for binary compatiblity */
2466
2467#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002468PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002469PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472}
2473
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002474#undef PyParser_SimpleParseString
2475PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002476PyParser_SimpleParseString(const char *str, int start)
2477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002480
2481#undef PyRun_AnyFile
2482PyAPI_FUNC(int)
2483PyRun_AnyFile(FILE *fp, const char *name)
2484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002486}
2487
2488#undef PyRun_AnyFileEx
2489PyAPI_FUNC(int)
2490PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002493}
2494
2495#undef PyRun_AnyFileFlags
2496PyAPI_FUNC(int)
2497PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002500}
2501
2502#undef PyRun_File
2503PyAPI_FUNC(PyObject *)
2504PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002507}
2508
2509#undef PyRun_FileEx
2510PyAPI_FUNC(PyObject *)
2511PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002514}
2515
2516#undef PyRun_FileFlags
2517PyAPI_FUNC(PyObject *)
2518PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002522}
2523
2524#undef PyRun_SimpleFile
2525PyAPI_FUNC(int)
2526PyRun_SimpleFile(FILE *f, const char *p)
2527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002529}
2530
2531#undef PyRun_SimpleFileEx
2532PyAPI_FUNC(int)
2533PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002536}
2537
2538
2539#undef PyRun_String
2540PyAPI_FUNC(PyObject *)
2541PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002544}
2545
2546#undef PyRun_SimpleString
2547PyAPI_FUNC(int)
2548PyRun_SimpleString(const char *s)
2549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002551}
2552
2553#undef Py_CompileString
2554PyAPI_FUNC(PyObject *)
2555Py_CompileString(const char *str, const char *p, int s)
2556{
Georg Brandl8334fd92010-12-04 10:26:46 +00002557 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2558}
2559
2560#undef Py_CompileStringFlags
2561PyAPI_FUNC(PyObject *)
2562Py_CompileStringFlags(const char *str, const char *p, int s,
2563 PyCompilerFlags *flags)
2564{
2565 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002566}
2567
2568#undef PyRun_InteractiveOne
2569PyAPI_FUNC(int)
2570PyRun_InteractiveOne(FILE *f, const char *p)
2571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002573}
2574
2575#undef PyRun_InteractiveLoop
2576PyAPI_FUNC(int)
2577PyRun_InteractiveLoop(FILE *f, const char *p)
2578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002580}
2581
2582#ifdef __cplusplus
2583}
2584#endif