blob: 44b817f5468b3f2cc54d52498bfd4fdc2093f673 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
43 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#endif
45
46#ifdef __cplusplus
47extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000048#endif
49
Martin v. Löwis790465f2008-04-05 20:41:37 +000050extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000051
Guido van Rossum82598051997-03-05 00:20:32 +000052extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossumb73cc041993-11-01 16:28:59 +000054/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static void initmain(void);
Victor Stinner793b5312011-04-27 00:24:21 +020056static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020065static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000067static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000068static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000069static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +020070extern int _PyUnicode_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000071extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020074extern int _PyFaulthandler_Init(void);
75extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000084int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000085int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020086int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000087int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000088int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000089int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000090int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000091int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000092int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000094int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000095
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020096PyThreadState *_Py_Finalizing = NULL;
97
Christian Heimes33fe8092008-04-13 13:53:33 +000098/* PyModule_GetWarningsModule is no longer necessary as of 2.6
99since _warnings is builtin. This API should not be used. */
100PyObject *
101PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000104}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000105
Guido van Rossum25ce5661997-08-02 03:10:38 +0000106static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000107
Thomas Wouters7e474022000-07-16 12:04:32 +0000108/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109
110int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000111Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000114}
115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116/* Global initializations. Can be undone by Py_Finalize(). Don't
117 call this twice without an intervening Py_Finalize() call. When
118 initializations fail, a fatal error is issued and the function does
119 not return. On return, the first thread and interpreter state have
120 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000121
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122 Locking: you must hold the interpreter lock while calling this.
123 (If the lock has not yet been initialized, that's equivalent to
124 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000125
Guido van Rossum25ce5661997-08-02 03:10:38 +0000126*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000127
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000128static int
129add_flag(int flag, const char *envs)
130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 int env = atoi(envs);
132 if (flag < env)
133 flag = env;
134 if (flag < 1)
135 flag = 1;
136 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000137}
138
Christian Heimes5833a2f2008-10-30 21:40:04 +0000139static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000140get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000141{
Victor Stinner94908bb2010-08-18 21:23:25 +0000142 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000143 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200144 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000145
Victor Stinner94908bb2010-08-18 21:23:25 +0000146 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 if (!codec)
148 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000149
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200150 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 Py_CLEAR(codec);
152 if (!name)
153 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000154
Victor Stinner94908bb2010-08-18 21:23:25 +0000155 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100156 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000157 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000158 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000160 if (name_str == NULL) {
161 PyErr_NoMemory();
162 return NULL;
163 }
164 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000165
166error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000168 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000170}
Victor Stinner94908bb2010-08-18 21:23:25 +0000171
Victor Stinner94908bb2010-08-18 21:23:25 +0000172static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200173get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000174{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200175#ifdef MS_WINDOWS
176 char codepage[100];
177 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
178 return get_codec_name(codepage);
179#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000180 char* codeset = nl_langinfo(CODESET);
181 if (!codeset || codeset[0] == '\0') {
182 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
183 return NULL;
184 }
185 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200186#else
187 PyErr_SetNone(PyExc_NotImplementedError);
188 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000189#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200190}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000191
Guido van Rossuma027efa1997-05-05 20:56:21 +0000192void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000193Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 PyInterpreterState *interp;
196 PyThreadState *tstate;
197 PyObject *bimod, *sysmod, *pstderr;
198 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if (initialized)
202 return;
203 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200204 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000205
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000206#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 /* Set up the LC_CTYPE locale, so we can obtain
208 the locale's charset without having to switch
209 locales. */
210 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000211#endif
212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
214 Py_DebugFlag = add_flag(Py_DebugFlag, p);
215 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
216 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
217 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
218 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
219 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
220 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 interp = PyInterpreterState_New();
223 if (interp == NULL)
224 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 tstate = PyThreadState_New(interp);
227 if (tstate == NULL)
228 Py_FatalError("Py_Initialize: can't make first thread");
229 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000230
Victor Stinner6961bd62010-08-17 22:26:51 +0000231#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000232 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
233 destroying the GIL might fail when it is being referenced from
234 another running thread (see issue #9901).
235 Instead we destroy the previously created GIL here, which ensures
236 that we can call Py_Initialize / Py_Finalize multiple times. */
237 _PyEval_FiniThreads();
238
239 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000240 _PyGILState_Init(interp, tstate);
241#endif /* WITH_THREAD */
242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (!_PyFrame_Init())
246 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (!_PyLong_Init())
249 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 if (!PyByteArray_Init())
252 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 interp->modules = PyDict_New();
257 if (interp->modules == NULL)
258 Py_FatalError("Py_Initialize: can't make modules dictionary");
259 interp->modules_reloading = PyDict_New();
260 if (interp->modules_reloading == NULL)
261 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200264 if (_PyUnicode_Init() < 0)
265 Py_FatalError("Py_Initialize: can't initialize unicode");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 bimod = _PyBuiltin_Init();
268 if (bimod == NULL)
269 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000270 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 interp->builtins = PyModule_GetDict(bimod);
272 if (interp->builtins == NULL)
273 Py_FatalError("Py_Initialize: can't initialize builtins dict");
274 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* initialize builtin exceptions */
277 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 sysmod = _PySys_Init();
280 if (sysmod == NULL)
281 Py_FatalError("Py_Initialize: can't initialize sys");
282 interp->sysdict = PyModule_GetDict(sysmod);
283 if (interp->sysdict == NULL)
284 Py_FatalError("Py_Initialize: can't initialize sys dict");
285 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000286 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 PySys_SetPath(Py_GetPath());
288 PyDict_SetItemString(interp->sysdict, "modules",
289 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 /* Set up a preliminary stderr printer until we have enough
292 infrastructure for the io module in place. */
293 pstderr = PyFile_NewStdPrinter(fileno(stderr));
294 if (pstderr == NULL)
295 Py_FatalError("Py_Initialize: can't set preliminary stderr");
296 PySys_SetObject("stderr", pstderr);
297 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000298 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000303
Victor Stinner024e37a2011-03-31 01:31:06 +0200304 /* initialize the faulthandler module */
305 if (_PyFaulthandler_Init())
306 Py_FatalError("Py_Initialize: can't initialize faulthandler");
307
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000308 /* Initialize _warnings. */
309 _PyWarnings_Init();
310
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000311 _PyTime_Init();
312
Victor Stinner793b5312011-04-27 00:24:21 +0200313 if (initfsencoding(interp) < 0)
314 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (install_sigs)
317 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 initmain(); /* Module __main__ */
320 if (initstdio() < 0)
321 Py_FatalError(
322 "Py_Initialize: can't initialize sys standard streams");
323
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000324 /* Initialize warnings. */
325 if (PySys_HasWarnOptions()) {
326 PyObject *warnings_module = PyImport_ImportModule("warnings");
327 if (warnings_module == NULL) {
328 fprintf(stderr, "'import warnings' failed; traceback:\n");
329 PyErr_Print();
330 }
331 Py_XDECREF(warnings_module);
332 }
333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (!Py_NoSiteFlag)
335 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000336}
337
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000338void
339Py_Initialize(void)
340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000342}
343
344
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000345#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000346extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000347#endif
348
Guido van Rossume8432ac2007-07-09 15:04:50 +0000349/* Flush stdout and stderr */
350
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100351static int
352file_is_closed(PyObject *fobj)
353{
354 int r;
355 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
356 if (tmp == NULL) {
357 PyErr_Clear();
358 return 0;
359 }
360 r = PyObject_IsTrue(tmp);
361 Py_DECREF(tmp);
362 if (r < 0)
363 PyErr_Clear();
364 return r > 0;
365}
366
Neal Norwitz2bad9702007-08-27 06:19:22 +0000367static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000368flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyObject *fout = PySys_GetObject("stdout");
371 PyObject *ferr = PySys_GetObject("stderr");
372 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200373 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000374
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100375 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200376 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000378 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 else
380 Py_DECREF(tmp);
381 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000382
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100383 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200384 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 if (tmp == NULL)
386 PyErr_Clear();
387 else
388 Py_DECREF(tmp);
389 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000390}
391
Guido van Rossum25ce5661997-08-02 03:10:38 +0000392/* Undo the effect of Py_Initialize().
393
394 Beware: if multiple interpreter and/or thread states exist, these
395 are not wiped out; only the current thread and interpreter state
396 are deleted. But since everything else is deleted, those other
397 interpreter and thread states should no longer be used.
398
399 (XXX We should do better, e.g. wipe out all interpreters and
400 threads.)
401
402 Locking: as above.
403
404*/
405
406void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000407Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 PyInterpreterState *interp;
410 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (!initialized)
413 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 /* The interpreter is still entirely intact at this point, and the
418 * exit funcs may be relying on that. In particular, if some thread
419 * or exit func is still waiting to do an import, the import machinery
420 * expects Py_IsInitialized() to return true. So don't say the
421 * interpreter is uninitialized until after the exit funcs have run.
422 * Note that Threading.py uses an exit func to do a join on all the
423 * threads created thru it, so this also protects pending imports in
424 * the threads created via Threading.
425 */
426 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 /* Get current thread state and interpreter pointer */
429 tstate = PyThreadState_GET();
430 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000431
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200432 /* Remaining threads (e.g. daemon threads) will automatically exit
433 after taking the GIL (in PyEval_RestoreThread()). */
434 _Py_Finalizing = tstate;
435 initialized = 0;
436
437 /* Flush stdout+stderr */
438 flush_std_files();
439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 /* Disable signal handling */
441 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* Clear type lookup cache */
444 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 /* Collect garbage. This may call finalizers; it's nice to call these
447 * before all modules are destroyed.
448 * XXX If a __del__ or weakref callback is triggered here, and tries to
449 * XXX import a module, bad things can happen, because Python no
450 * XXX longer believes it's initialized.
451 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
452 * XXX is easy to provoke that way. I've also seen, e.g.,
453 * XXX Exception exceptions.ImportError: 'No module named sha'
454 * XXX in <function callback at 0x008F5718> ignored
455 * XXX but I'm unclear on exactly how that one happens. In any case,
456 * XXX I haven't seen a real-life report of either of these.
457 */
458 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000459#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 /* With COUNT_ALLOCS, it helps to run GC multiple times:
461 each collection might release some types from the type
462 list, so they become garbage. */
463 while (PyGC_Collect() > 0)
464 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000465#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000466 /* We run this while most interpreter state is still alive, so that
467 debug information can be printed out */
468 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 /* Destroy all modules */
471 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 /* Flush stdout+stderr (again, in case more was printed) */
474 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100477 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 * XXX This is disabled because it caused too many problems. If
479 * XXX a __del__ or weakref callback triggers here, Python code has
480 * XXX a hard time running, because even the sys module has been
481 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
482 * XXX One symptom is a sequence of information-free messages
483 * XXX coming from threads (if a __del__ or callback is invoked,
484 * XXX other threads can execute too, and any exception they encounter
485 * XXX triggers a comedy of errors as subsystem after subsystem
486 * XXX fails to find what it *expects* to find in sys to help report
487 * XXX the exception and consequent unexpected failures). I've also
488 * XXX seen segfaults then, after adding print statements to the
489 * XXX Python code getting called.
490 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000491#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000493#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
496 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000497
Victor Stinner024e37a2011-03-31 01:31:06 +0200498 /* unload faulthandler module */
499 _PyFaulthandler_Fini();
500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000502#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000504#endif
505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000507
Tim Peters9cf25ce2003-04-17 15:21:01 +0000508#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* Display all objects still alive -- this can invoke arbitrary
510 * __repr__ overrides, so requires a mostly-intact interpreter.
511 * Alas, a lot of stuff may still be alive now that will be cleaned
512 * up later.
513 */
514 if (Py_GETENV("PYTHONDUMPREFS"))
515 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000516#endif /* Py_TRACE_REFS */
517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* Clear interpreter state */
519 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 /* Now we decref the exception classes. After this point nothing
522 can raise an exception. That's okay, because each Fini() method
523 below has been checked to make sure no exceptions are ever
524 raised.
525 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000530#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000532#endif /* WITH_THREAD */
533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 /* Delete current thread */
535 PyThreadState_Swap(NULL);
536 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 /* Sundry finalizers */
539 PyMethod_Fini();
540 PyFrame_Fini();
541 PyCFunction_Fini();
542 PyTuple_Fini();
543 PyList_Fini();
544 PySet_Fini();
545 PyBytes_Fini();
546 PyByteArray_Fini();
547 PyLong_Fini();
548 PyFloat_Fini();
549 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100550 PySlice_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 /* Cleanup Unicode implementation */
553 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000556 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 free((char*)Py_FileSystemDefaultEncoding);
558 Py_FileSystemDefaultEncoding = NULL;
559 }
Christian Heimesc8967002007-11-30 10:18:26 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 /* XXX Still allocated:
562 - various static ad-hoc pointers to interned strings
563 - int and float free list blocks
564 - whatever various modules and libraries allocate
565 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000568
Tim Peters269b2a62003-04-17 19:52:29 +0000569#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 /* Display addresses (& refcnts) of all objects still alive.
571 * An address can be used to find the repr of the object, printed
572 * above by _Py_PrintReferences.
573 */
574 if (Py_GETENV("PYTHONDUMPREFS"))
575 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000576#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000577#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (Py_GETENV("PYTHONMALLOCSTATS"))
579 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000580#endif
581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000583}
584
585/* Create and initialize a new interpreter and thread, and return the
586 new thread. This requires that Py_Initialize() has been called
587 first.
588
589 Unsuccessful initialization yields a NULL pointer. Note that *no*
590 exception information is available even in this case -- the
591 exception information is held in the thread, and there is no
592 thread.
593
594 Locking: as above.
595
596*/
597
598PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000599Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyInterpreterState *interp;
602 PyThreadState *tstate, *save_tstate;
603 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (!initialized)
606 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 interp = PyInterpreterState_New();
609 if (interp == NULL)
610 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 tstate = PyThreadState_New(interp);
613 if (tstate == NULL) {
614 PyInterpreterState_Delete(interp);
615 return NULL;
616 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 interp->modules = PyDict_New();
623 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000624
Victor Stinner49d3f252010-10-17 01:24:53 +0000625 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (bimod != NULL) {
627 interp->builtins = PyModule_GetDict(bimod);
628 if (interp->builtins == NULL)
629 goto handle_error;
630 Py_INCREF(interp->builtins);
631 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 /* initialize builtin exceptions */
634 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000635
Victor Stinner49d3f252010-10-17 01:24:53 +0000636 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (bimod != NULL && sysmod != NULL) {
638 PyObject *pstderr;
639 interp->sysdict = PyModule_GetDict(sysmod);
640 if (interp->sysdict == NULL)
641 goto handle_error;
642 Py_INCREF(interp->sysdict);
643 PySys_SetPath(Py_GetPath());
644 PyDict_SetItemString(interp->sysdict, "modules",
645 interp->modules);
646 /* Set up a preliminary stderr printer until we have enough
647 infrastructure for the io module in place. */
648 pstderr = PyFile_NewStdPrinter(fileno(stderr));
649 if (pstderr == NULL)
650 Py_FatalError("Py_Initialize: can't set preliminary stderr");
651 PySys_SetObject("stderr", pstderr);
652 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000653 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200656
657 if (initfsencoding(interp) < 0)
658 goto handle_error;
659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (initstdio() < 0)
661 Py_FatalError(
662 "Py_Initialize: can't initialize sys standard streams");
663 initmain();
664 if (!Py_NoSiteFlag)
665 initsite();
666 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (!PyErr_Occurred())
669 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000670
Thomas Wouters89f507f2006-12-13 04:49:30 +0000671handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000673
Victor Stinnerc40a3502011-04-27 00:20:27 +0200674 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 PyThreadState_Clear(tstate);
676 PyThreadState_Swap(save_tstate);
677 PyThreadState_Delete(tstate);
678 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000681}
682
683/* Delete an interpreter and its last thread. This requires that the
684 given thread state is current, that the thread has no remaining
685 frames, and that it is its interpreter's only remaining thread.
686 It is a fatal error to violate these constraints.
687
688 (Py_Finalize() doesn't have these constraints -- it zaps
689 everything, regardless.)
690
691 Locking: as above.
692
693*/
694
695void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000696Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 if (tstate != PyThreadState_GET())
701 Py_FatalError("Py_EndInterpreter: thread is not current");
702 if (tstate->frame != NULL)
703 Py_FatalError("Py_EndInterpreter: thread still has a frame");
704 if (tstate != interp->tstate_head || tstate->next != NULL)
705 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 PyImport_Cleanup();
708 PyInterpreterState_Clear(interp);
709 PyThreadState_Swap(NULL);
710 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000711}
712
Martin v. Löwis790465f2008-04-05 20:41:37 +0000713static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000714
715void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000716Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (pn && *pn)
719 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000720}
721
Martin v. Löwis790465f2008-04-05 20:41:37 +0000722wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000723Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000726}
727
Martin v. Löwis790465f2008-04-05 20:41:37 +0000728static wchar_t *default_home = NULL;
729static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000730
731void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000732Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000735}
736
Martin v. Löwis790465f2008-04-05 20:41:37 +0000737wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000738Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 wchar_t *home = default_home;
741 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
742 char* chome = Py_GETENV("PYTHONHOME");
743 if (chome) {
744 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
745 if (r != (size_t)-1 && r <= PATH_MAX)
746 home = env_home;
747 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 }
750 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000751}
752
Guido van Rossum6135a871995-01-09 17:53:26 +0000753/* Create __main__ module */
754
755static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000756initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyObject *m, *d;
759 m = PyImport_AddModule("__main__");
760 if (m == NULL)
761 Py_FatalError("can't create __main__ module");
762 d = PyModule_GetDict(m);
763 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
764 PyObject *bimod = PyImport_ImportModule("builtins");
765 if (bimod == NULL ||
766 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
767 Py_FatalError("can't add __builtins__ to __main__");
768 Py_DECREF(bimod);
769 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000770}
771
Victor Stinner793b5312011-04-27 00:24:21 +0200772static int
773initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000774{
775 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000776
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200777 if (Py_FileSystemDefaultEncoding == NULL)
778 {
779 Py_FileSystemDefaultEncoding = get_locale_encoding();
780 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000781 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000782
Victor Stinnere4743092010-10-19 00:05:51 +0000783 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200784 interp->fscodec_initialized = 1;
785 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000786 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000787
788 /* the encoding is mbcs, utf-8 or ascii */
789 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
790 if (!codec) {
791 /* Such error can only occurs in critical situations: no more
792 * memory, import a module of the standard library failed,
793 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200794 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000795 }
Victor Stinner793b5312011-04-27 00:24:21 +0200796 Py_DECREF(codec);
797 interp->fscodec_initialized = 1;
798 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000799}
800
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000801/* Import the site module (not into __main__ though) */
802
803static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000804initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyObject *m;
807 m = PyImport_ImportModule("site");
808 if (m == NULL) {
809 PyErr_Print();
810 Py_Finalize();
811 exit(1);
812 }
813 else {
814 Py_DECREF(m);
815 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000816}
817
Antoine Pitrou05608432009-01-09 18:53:14 +0000818static PyObject*
819create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 int fd, int write_mode, char* name,
821 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
824 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000825 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PyObject *line_buffering;
827 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200828 _Py_IDENTIFIER(open);
829 _Py_IDENTIFIER(isatty);
830 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200831 _Py_IDENTIFIER(name);
832 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 /* stdin is always opened in buffered mode, first because it shouldn't
835 make a difference in common use cases, second because TextIOWrapper
836 depends on the presence of a read1() method which only exists on
837 buffered streams.
838 */
839 if (Py_UnbufferedStdioFlag && write_mode)
840 buffering = 0;
841 else
842 buffering = -1;
843 if (write_mode)
844 mode = "wb";
845 else
846 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200847 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
848 fd, mode, buffering,
849 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (buf == NULL)
851 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200854 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200855 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (raw == NULL)
857 goto error;
858 }
859 else {
860 raw = buf;
861 Py_INCREF(raw);
862 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200865 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200867 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (res == NULL)
869 goto error;
870 isatty = PyObject_IsTrue(res);
871 Py_DECREF(res);
872 if (isatty == -1)
873 goto error;
874 if (isatty || Py_UnbufferedStdioFlag)
875 line_buffering = Py_True;
876 else
877 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 Py_CLEAR(raw);
880 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000881
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000882 newline = "\n";
883#ifdef MS_WINDOWS
884 if (!write_mode) {
885 /* translate \r\n to \n for sys.stdin on Windows */
886 newline = NULL;
887 }
888#endif
889
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200890 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
891 buf, encoding, errors,
892 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 Py_CLEAR(buf);
894 if (stream == NULL)
895 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 if (write_mode)
898 mode = "w";
899 else
900 mode = "r";
901 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200902 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 goto error;
904 Py_CLEAR(text);
905 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000906
907error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 Py_XDECREF(buf);
909 Py_XDECREF(stream);
910 Py_XDECREF(text);
911 Py_XDECREF(raw);
912 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000913}
914
Antoine Pitrou11942a52011-11-28 19:08:36 +0100915static int
916is_valid_fd(int fd)
917{
918 int dummy_fd;
919 if (fd < 0 || !_PyVerify_fd(fd))
920 return 0;
921 dummy_fd = dup(fd);
922 if (dummy_fd < 0)
923 return 0;
924 close(dummy_fd);
925 return 1;
926}
927
Georg Brandl1a3284e2007-12-02 09:40:06 +0000928/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000929static int
930initstdio(void)
931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 PyObject *iomod = NULL, *wrapper;
933 PyObject *bimod = NULL;
934 PyObject *m;
935 PyObject *std = NULL;
936 int status = 0, fd;
937 PyObject * encoding_attr;
938 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 /* Hack to avoid a nasty recursion issue when Python is invoked
941 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
942 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
943 goto error;
944 }
945 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
948 goto error;
949 }
950 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 if (!(bimod = PyImport_ImportModule("builtins"))) {
953 goto error;
954 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (!(iomod = PyImport_ImportModule("io"))) {
957 goto error;
958 }
959 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
960 goto error;
961 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* Set builtins.open */
964 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000965 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 goto error;
967 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000968 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 encoding = Py_GETENV("PYTHONIOENCODING");
971 errors = NULL;
972 if (encoding) {
973 encoding = strdup(encoding);
974 errors = strchr(encoding, ':');
975 if (errors) {
976 *errors = '\0';
977 errors++;
978 }
979 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 /* Set sys.stdin */
982 fd = fileno(stdin);
983 /* Under some conditions stdin, stdout and stderr may not be connected
984 * and fileno() may point to an invalid file descriptor. For example
985 * GUI apps don't have valid standard streams by default.
986 */
Antoine Pitrou11942a52011-11-28 19:08:36 +0100987 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 std = Py_None;
989 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 }
991 else {
992 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
993 if (std == NULL)
994 goto error;
995 } /* if (fd < 0) */
996 PySys_SetObject("__stdin__", std);
997 PySys_SetObject("stdin", std);
998 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 /* Set sys.stdout */
1001 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001002 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 std = Py_None;
1004 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 }
1006 else {
1007 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1008 if (std == NULL)
1009 goto error;
1010 } /* if (fd < 0) */
1011 PySys_SetObject("__stdout__", std);
1012 PySys_SetObject("stdout", std);
1013 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001014
Guido van Rossum98297ee2007-11-06 21:34:58 +00001015#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 /* Set sys.stderr, replaces the preliminary stderr */
1017 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001018 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 std = Py_None;
1020 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 }
1022 else {
1023 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1024 if (std == NULL)
1025 goto error;
1026 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* Same as hack above, pre-import stderr's codec to avoid recursion
1029 when import.c tries to write to stderr in verbose mode. */
1030 encoding_attr = PyObject_GetAttrString(std, "encoding");
1031 if (encoding_attr != NULL) {
1032 const char * encoding;
1033 encoding = _PyUnicode_AsString(encoding_attr);
1034 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001035 PyObject *codec_info = _PyCodec_Lookup(encoding);
1036 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001038 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 }
1040 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PySys_SetObject("__stderr__", std);
1043 PySys_SetObject("stderr", std);
1044 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001045#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001048 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 status = -1;
1050 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 if (encoding)
1053 free(encoding);
1054 Py_XDECREF(bimod);
1055 Py_XDECREF(iomod);
1056 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001057}
1058
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001059/* Parse input from a file and execute it */
1060
1061int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001062PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 if (filename == NULL)
1066 filename = "???";
1067 if (Py_FdIsInteractive(fp, filename)) {
1068 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1069 if (closeit)
1070 fclose(fp);
1071 return err;
1072 }
1073 else
1074 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001075}
1076
1077int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001078PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 PyObject *v;
1081 int ret;
1082 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (flags == NULL) {
1085 flags = &local_flags;
1086 local_flags.cf_flags = 0;
1087 }
1088 v = PySys_GetObject("ps1");
1089 if (v == NULL) {
1090 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1091 Py_XDECREF(v);
1092 }
1093 v = PySys_GetObject("ps2");
1094 if (v == NULL) {
1095 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1096 Py_XDECREF(v);
1097 }
1098 for (;;) {
1099 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1100 PRINT_TOTAL_REFS();
1101 if (ret == E_EOF)
1102 return 0;
1103 /*
1104 if (ret == E_NOMEM)
1105 return -1;
1106 */
1107 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001108}
1109
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001110/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001111static int PARSER_FLAGS(PyCompilerFlags *flags)
1112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 int parser_flags = 0;
1114 if (!flags)
1115 return 0;
1116 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1117 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1118 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1119 parser_flags |= PyPARSE_IGNORE_COOKIE;
1120 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1121 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1122 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001123}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001124
Thomas Wouters89f507f2006-12-13 04:49:30 +00001125#if 0
1126/* Keep an example of flags with future keyword support. */
1127#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1129 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1130 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1131 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001132#endif
1133
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001134int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001135PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 PyObject *m, *d, *v, *w, *oenc = NULL;
1138 mod_ty mod;
1139 PyArena *arena;
1140 char *ps1 = "", *ps2 = "", *enc = NULL;
1141 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001142 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (fp == stdin) {
1145 /* Fetch encoding from sys.stdin */
1146 v = PySys_GetObject("stdin");
1147 if (v == NULL || v == Py_None)
1148 return -1;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001149 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (!oenc)
1151 return -1;
1152 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001153 if (enc == NULL)
1154 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 }
1156 v = PySys_GetObject("ps1");
1157 if (v != NULL) {
1158 v = PyObject_Str(v);
1159 if (v == NULL)
1160 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001161 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001163 if (ps1 == NULL) {
1164 PyErr_Clear();
1165 ps1 = "";
1166 }
1167 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 }
1169 w = PySys_GetObject("ps2");
1170 if (w != NULL) {
1171 w = PyObject_Str(w);
1172 if (w == NULL)
1173 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001174 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001176 if (ps2 == NULL) {
1177 PyErr_Clear();
1178 ps2 = "";
1179 }
1180 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 }
1182 arena = PyArena_New();
1183 if (arena == NULL) {
1184 Py_XDECREF(v);
1185 Py_XDECREF(w);
1186 Py_XDECREF(oenc);
1187 return -1;
1188 }
1189 mod = PyParser_ASTFromFile(fp, filename, enc,
1190 Py_single_input, ps1, ps2,
1191 flags, &errcode, arena);
1192 Py_XDECREF(v);
1193 Py_XDECREF(w);
1194 Py_XDECREF(oenc);
1195 if (mod == NULL) {
1196 PyArena_Free(arena);
1197 if (errcode == E_EOF) {
1198 PyErr_Clear();
1199 return E_EOF;
1200 }
1201 PyErr_Print();
1202 return -1;
1203 }
1204 m = PyImport_AddModule("__main__");
1205 if (m == NULL) {
1206 PyArena_Free(arena);
1207 return -1;
1208 }
1209 d = PyModule_GetDict(m);
1210 v = run_mod(mod, filename, d, d, flags, arena);
1211 PyArena_Free(arena);
1212 flush_io();
1213 if (v == NULL) {
1214 PyErr_Print();
1215 return -1;
1216 }
1217 Py_DECREF(v);
1218 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001219}
1220
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001221/* Check whether a file maybe a pyc file: Look at the extension,
1222 the file type, and, if we may close it, at the first few bytes. */
1223
1224static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001225maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1228 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 /* Only look into the file if we are allowed to close it, since
1231 it then should also be seekable. */
1232 if (closeit) {
1233 /* Read only two bytes of the magic. If the file was opened in
1234 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1235 be read as they are on disk. */
1236 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1237 unsigned char buf[2];
1238 /* Mess: In case of -x, the stream is NOT at its start now,
1239 and ungetc() was used to push back the first newline,
1240 which makes the current stream position formally undefined,
1241 and a x-platform nightmare.
1242 Unfortunately, we have no direct way to know whether -x
1243 was specified. So we use a terrible hack: if the current
1244 stream position is not 0, we assume -x was specified, and
1245 give up. Bug 132850 on SourceForge spells out the
1246 hopelessness of trying anything else (fseek and ftell
1247 don't work predictably x-platform for text-mode files).
1248 */
1249 int ispyc = 0;
1250 if (ftell(fp) == 0) {
1251 if (fread(buf, 1, 2, fp) == 2 &&
1252 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1253 ispyc = 1;
1254 rewind(fp);
1255 }
1256 return ispyc;
1257 }
1258 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001259}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001260
Guido van Rossum0df002c2000-08-27 19:21:52 +00001261int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001262PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 PyObject *m, *d, *v;
1266 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001267 int set_file_name = 0, ret;
1268 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 m = PyImport_AddModule("__main__");
1271 if (m == NULL)
1272 return -1;
1273 d = PyModule_GetDict(m);
1274 if (PyDict_GetItemString(d, "__file__") == NULL) {
1275 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001276 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (f == NULL)
1278 return -1;
1279 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1280 Py_DECREF(f);
1281 return -1;
1282 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001283 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1284 Py_DECREF(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 return -1;
Barry Warsaw916048d2011-09-20 14:45:44 -04001286 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 set_file_name = 1;
1288 Py_DECREF(f);
1289 }
1290 len = strlen(filename);
1291 ext = filename + len - (len > 4 ? 4 : 0);
1292 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1293 /* Try to run a pyc file. First, re-open in binary */
1294 if (closeit)
1295 fclose(fp);
1296 if ((fp = fopen(filename, "rb")) == NULL) {
1297 fprintf(stderr, "python: Can't reopen .pyc file\n");
1298 ret = -1;
1299 goto done;
1300 }
1301 /* Turn on optimization if a .pyo file is given */
1302 if (strcmp(ext, ".pyo") == 0)
1303 Py_OptimizeFlag = 1;
1304 v = run_pyc_file(fp, filename, d, d, flags);
1305 } else {
1306 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1307 closeit, flags);
1308 }
1309 flush_io();
1310 if (v == NULL) {
1311 PyErr_Print();
1312 ret = -1;
1313 goto done;
1314 }
1315 Py_DECREF(v);
1316 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001317 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1319 PyErr_Clear();
1320 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001321}
1322
1323int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001324PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 PyObject *m, *d, *v;
1327 m = PyImport_AddModule("__main__");
1328 if (m == NULL)
1329 return -1;
1330 d = PyModule_GetDict(m);
1331 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1332 if (v == NULL) {
1333 PyErr_Print();
1334 return -1;
1335 }
1336 Py_DECREF(v);
1337 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001338}
1339
Barry Warsaw035574d1997-08-29 22:07:17 +00001340static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001341parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 long hold;
1345 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001346 _Py_IDENTIFIER(msg);
1347 _Py_IDENTIFIER(filename);
1348 _Py_IDENTIFIER(lineno);
1349 _Py_IDENTIFIER(offset);
1350 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001353
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001354 if (! (v = _PyObject_GetAttrId(err, &PyId_msg)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 goto finally;
1356 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001357
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001358 if (!(v = _PyObject_GetAttrId(err, &PyId_filename)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 goto finally;
1360 if (v == Py_None)
1361 *filename = NULL;
1362 else if (! (*filename = _PyUnicode_AsString(v)))
1363 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 Py_DECREF(v);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001366 if (!(v = _PyObject_GetAttrId(err, &PyId_lineno)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 goto finally;
1368 hold = PyLong_AsLong(v);
1369 Py_DECREF(v);
1370 v = NULL;
1371 if (hold < 0 && PyErr_Occurred())
1372 goto finally;
1373 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001374
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001375 if (!(v = _PyObject_GetAttrId(err, &PyId_offset)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 goto finally;
1377 if (v == Py_None) {
1378 *offset = -1;
1379 Py_DECREF(v);
1380 v = NULL;
1381 } else {
1382 hold = PyLong_AsLong(v);
1383 Py_DECREF(v);
1384 v = NULL;
1385 if (hold < 0 && PyErr_Occurred())
1386 goto finally;
1387 *offset = (int)hold;
1388 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001389
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001390 if (!(v = _PyObject_GetAttrId(err, &PyId_text)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 goto finally;
1392 if (v == Py_None)
1393 *text = NULL;
1394 else if (!PyUnicode_Check(v) ||
1395 !(*text = _PyUnicode_AsString(v)))
1396 goto finally;
1397 Py_DECREF(v);
1398 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001399
1400finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 Py_XDECREF(v);
1402 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001403}
1404
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001405void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001406PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001409}
1410
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001411static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001412print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 char *nl;
1415 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001416 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1417 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 for (;;) {
1419 nl = strchr(text, '\n');
1420 if (nl == NULL || nl-text >= offset)
1421 break;
1422 offset -= (int)(nl+1-text);
1423 text = nl+1;
1424 }
1425 while (*text == ' ' || *text == '\t') {
1426 text++;
1427 offset--;
1428 }
1429 }
1430 PyFile_WriteString(" ", f);
1431 PyFile_WriteString(text, f);
1432 if (*text == '\0' || text[strlen(text)-1] != '\n')
1433 PyFile_WriteString("\n", f);
1434 if (offset == -1)
1435 return;
1436 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001437 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001440}
1441
Guido van Rossum66e8e862001-03-23 17:54:43 +00001442static void
1443handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 PyObject *exception, *value, *tb;
1446 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (Py_InspectFlag)
1449 /* Don't exit if -i flag was given. This flag is set to 0
1450 * when entering interactive mode for inspecting. */
1451 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyErr_Fetch(&exception, &value, &tb);
1454 fflush(stdout);
1455 if (value == NULL || value == Py_None)
1456 goto done;
1457 if (PyExceptionInstance_Check(value)) {
1458 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001459 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001460 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 if (code) {
1462 Py_DECREF(value);
1463 value = code;
1464 if (value == Py_None)
1465 goto done;
1466 }
1467 /* If we failed to dig out the 'code' attribute,
1468 just let the else clause below print the error. */
1469 }
1470 if (PyLong_Check(value))
1471 exitcode = (int)PyLong_AsLong(value);
1472 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001473 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001474 if (sys_stderr != NULL && sys_stderr != Py_None) {
1475 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1476 } else {
1477 PyObject_Print(value, stderr, Py_PRINT_RAW);
1478 fflush(stderr);
1479 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PySys_WriteStderr("\n");
1481 exitcode = 1;
1482 }
Tim Peterscf615b52003-04-19 18:47:02 +00001483 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 /* Restore and clear the exception info, in order to properly decref
1485 * the exception, value, and traceback. If we just exit instead,
1486 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1487 * some finalizers from running.
1488 */
1489 PyErr_Restore(exception, value, tb);
1490 PyErr_Clear();
1491 Py_Exit(exitcode);
1492 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001493}
1494
1495void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001496PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1501 handle_system_exit();
1502 }
1503 PyErr_Fetch(&exception, &v, &tb);
1504 if (exception == NULL)
1505 return;
1506 PyErr_NormalizeException(&exception, &v, &tb);
1507 if (tb == NULL) {
1508 tb = Py_None;
1509 Py_INCREF(tb);
1510 }
1511 PyException_SetTraceback(v, tb);
1512 if (exception == NULL)
1513 return;
1514 /* Now we know v != NULL too */
1515 if (set_sys_last_vars) {
1516 PySys_SetObject("last_type", exception);
1517 PySys_SetObject("last_value", v);
1518 PySys_SetObject("last_traceback", tb);
1519 }
1520 hook = PySys_GetObject("excepthook");
1521 if (hook) {
1522 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1523 PyObject *result = PyEval_CallObject(hook, args);
1524 if (result == NULL) {
1525 PyObject *exception2, *v2, *tb2;
1526 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1527 handle_system_exit();
1528 }
1529 PyErr_Fetch(&exception2, &v2, &tb2);
1530 PyErr_NormalizeException(&exception2, &v2, &tb2);
1531 /* It should not be possible for exception2 or v2
1532 to be NULL. However PyErr_Display() can't
1533 tolerate NULLs, so just be safe. */
1534 if (exception2 == NULL) {
1535 exception2 = Py_None;
1536 Py_INCREF(exception2);
1537 }
1538 if (v2 == NULL) {
1539 v2 = Py_None;
1540 Py_INCREF(v2);
1541 }
1542 fflush(stdout);
1543 PySys_WriteStderr("Error in sys.excepthook:\n");
1544 PyErr_Display(exception2, v2, tb2);
1545 PySys_WriteStderr("\nOriginal exception was:\n");
1546 PyErr_Display(exception, v, tb);
1547 Py_DECREF(exception2);
1548 Py_DECREF(v2);
1549 Py_XDECREF(tb2);
1550 }
1551 Py_XDECREF(result);
1552 Py_XDECREF(args);
1553 } else {
1554 PySys_WriteStderr("sys.excepthook is missing\n");
1555 PyErr_Display(exception, v, tb);
1556 }
1557 Py_XDECREF(exception);
1558 Py_XDECREF(v);
1559 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001560}
1561
Benjamin Petersone6528212008-07-15 15:32:09 +00001562static void
1563print_exception(PyObject *f, PyObject *value)
1564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 int err = 0;
1566 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001567 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (!PyExceptionInstance_Check(value)) {
1570 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1571 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1572 PyFile_WriteString(" found\n", f);
1573 return;
1574 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 Py_INCREF(value);
1577 fflush(stdout);
1578 type = (PyObject *) Py_TYPE(value);
1579 tb = PyException_GetTraceback(value);
1580 if (tb && tb != Py_None)
1581 err = PyTraceBack_Print(tb, f);
1582 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001583 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 {
1585 PyObject *message;
1586 const char *filename, *text;
1587 int lineno, offset;
1588 if (!parse_syntax_error(value, &message, &filename,
1589 &lineno, &offset, &text))
1590 PyErr_Clear();
1591 else {
1592 char buf[10];
1593 PyFile_WriteString(" File \"", f);
1594 if (filename == NULL)
1595 PyFile_WriteString("<string>", f);
1596 else
1597 PyFile_WriteString(filename, f);
1598 PyFile_WriteString("\", line ", f);
1599 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1600 PyFile_WriteString(buf, f);
1601 PyFile_WriteString("\n", f);
1602 if (text != NULL)
1603 print_error_text(f, offset, text);
1604 Py_DECREF(value);
1605 value = message;
1606 /* Can't be bothered to check all those
1607 PyFile_WriteString() calls */
1608 if (PyErr_Occurred())
1609 err = -1;
1610 }
1611 }
1612 if (err) {
1613 /* Don't do anything else */
1614 }
1615 else {
1616 PyObject* moduleName;
1617 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001618 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 assert(PyExceptionClass_Check(type));
1620 className = PyExceptionClass_Name(type);
1621 if (className != NULL) {
1622 char *dot = strrchr(className, '.');
1623 if (dot != NULL)
1624 className = dot+1;
1625 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001626
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001627 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1629 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001630 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 err = PyFile_WriteString("<unknown>", f);
1632 }
1633 else {
1634 char* modstr = _PyUnicode_AsString(moduleName);
1635 if (modstr && strcmp(modstr, "builtins"))
1636 {
1637 err = PyFile_WriteString(modstr, f);
1638 err += PyFile_WriteString(".", f);
1639 }
1640 Py_DECREF(moduleName);
1641 }
1642 if (err == 0) {
1643 if (className == NULL)
1644 err = PyFile_WriteString("<unknown>", f);
1645 else
1646 err = PyFile_WriteString(className, f);
1647 }
1648 }
1649 if (err == 0 && (value != Py_None)) {
1650 PyObject *s = PyObject_Str(value);
1651 /* only print colon if the str() of the
1652 object is not the empty string
1653 */
1654 if (s == NULL)
1655 err = -1;
1656 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001657 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 err = PyFile_WriteString(": ", f);
1659 if (err == 0)
1660 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1661 Py_XDECREF(s);
1662 }
1663 /* try to write a newline in any case */
1664 err += PyFile_WriteString("\n", f);
1665 Py_XDECREF(tb);
1666 Py_DECREF(value);
1667 /* If an error happened here, don't show it.
1668 XXX This is wrong, but too many callers rely on this behavior. */
1669 if (err != 0)
1670 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001671}
1672
1673static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 "\nThe above exception was the direct cause "
1675 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001676
1677static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 "\nDuring handling of the above exception, "
1679 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001680
1681static void
1682print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 int err = 0, res;
1685 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (seen != NULL) {
1688 /* Exception chaining */
1689 if (PySet_Add(seen, value) == -1)
1690 PyErr_Clear();
1691 else if (PyExceptionInstance_Check(value)) {
1692 cause = PyException_GetCause(value);
1693 context = PyException_GetContext(value);
1694 if (cause) {
1695 res = PySet_Contains(seen, cause);
1696 if (res == -1)
1697 PyErr_Clear();
1698 if (res == 0) {
1699 print_exception_recursive(
1700 f, cause, seen);
1701 err |= PyFile_WriteString(
1702 cause_message, f);
1703 }
1704 }
1705 else if (context) {
1706 res = PySet_Contains(seen, context);
1707 if (res == -1)
1708 PyErr_Clear();
1709 if (res == 0) {
1710 print_exception_recursive(
1711 f, context, seen);
1712 err |= PyFile_WriteString(
1713 context_message, f);
1714 }
1715 }
1716 Py_XDECREF(context);
1717 Py_XDECREF(cause);
1718 }
1719 }
1720 print_exception(f, value);
1721 if (err != 0)
1722 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001723}
1724
Thomas Wouters477c8d52006-05-27 19:21:47 +00001725void
1726PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 PyObject *seen;
1729 PyObject *f = PySys_GetObject("stderr");
1730 if (f == Py_None) {
1731 /* pass */
1732 }
1733 else if (f == NULL) {
1734 _PyObject_Dump(value);
1735 fprintf(stderr, "lost sys.stderr\n");
1736 }
1737 else {
1738 /* We choose to ignore seen being possibly NULL, and report
1739 at least the main exception (it could be a MemoryError).
1740 */
1741 seen = PySet_New(NULL);
1742 if (seen == NULL)
1743 PyErr_Clear();
1744 print_exception_recursive(f, value, seen);
1745 Py_XDECREF(seen);
1746 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001747}
1748
Guido van Rossum82598051997-03-05 00:20:32 +00001749PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001750PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 PyObject *ret = NULL;
1754 mod_ty mod;
1755 PyArena *arena = PyArena_New();
1756 if (arena == NULL)
1757 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1760 if (mod != NULL)
1761 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1762 PyArena_Free(arena);
1763 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001764}
1765
1766PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001767PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 PyObject *ret;
1771 mod_ty mod;
1772 PyArena *arena = PyArena_New();
1773 if (arena == NULL)
1774 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1777 flags, NULL, arena);
1778 if (closeit)
1779 fclose(fp);
1780 if (mod == NULL) {
1781 PyArena_Free(arena);
1782 return NULL;
1783 }
1784 ret = run_mod(mod, filename, globals, locals, flags, arena);
1785 PyArena_Free(arena);
1786 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001787}
1788
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001789static void
1790flush_io(void)
1791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 PyObject *f, *r;
1793 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001794 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 /* Save the current exception */
1797 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 f = PySys_GetObject("stderr");
1800 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001801 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 if (r)
1803 Py_DECREF(r);
1804 else
1805 PyErr_Clear();
1806 }
1807 f = PySys_GetObject("stdout");
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 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001817}
1818
Guido van Rossum82598051997-03-05 00:20:32 +00001819static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001820run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 PyCodeObject *co;
1824 PyObject *v;
1825 co = PyAST_Compile(mod, filename, flags, arena);
1826 if (co == NULL)
1827 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001828 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 Py_DECREF(co);
1830 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001831}
1832
Guido van Rossum82598051997-03-05 00:20:32 +00001833static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001834run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 PyCodeObject *co;
1838 PyObject *v;
1839 long magic;
1840 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 magic = PyMarshal_ReadLongFromFile(fp);
1843 if (magic != PyImport_GetMagicNumber()) {
1844 PyErr_SetString(PyExc_RuntimeError,
1845 "Bad magic number in .pyc file");
1846 return NULL;
1847 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001848 /* Skip mtime and size */
1849 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 (void) PyMarshal_ReadLongFromFile(fp);
1851 v = PyMarshal_ReadLastObjectFromFile(fp);
1852 fclose(fp);
1853 if (v == NULL || !PyCode_Check(v)) {
1854 Py_XDECREF(v);
1855 PyErr_SetString(PyExc_RuntimeError,
1856 "Bad code object in .pyc file");
1857 return NULL;
1858 }
1859 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001860 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 if (v && flags)
1862 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1863 Py_DECREF(co);
1864 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001865}
1866
Guido van Rossum82598051997-03-05 00:20:32 +00001867PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001868Py_CompileStringExFlags(const char *str, const char *filename, int start,
1869 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 PyCodeObject *co;
1872 mod_ty mod;
1873 PyArena *arena = PyArena_New();
1874 if (arena == NULL)
1875 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1878 if (mod == NULL) {
1879 PyArena_Free(arena);
1880 return NULL;
1881 }
1882 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1883 PyObject *result = PyAST_mod2obj(mod);
1884 PyArena_Free(arena);
1885 return result;
1886 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001887 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 PyArena_Free(arena);
1889 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001890}
1891
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001892/* For use in Py_LIMITED_API */
1893#undef Py_CompileString
1894PyObject *
1895PyCompileString(const char *str, const char *filename, int start)
1896{
1897 return Py_CompileStringFlags(str, filename, start, NULL);
1898}
1899
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001900struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001901Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 struct symtable *st;
1904 mod_ty mod;
1905 PyCompilerFlags flags;
1906 PyArena *arena = PyArena_New();
1907 if (arena == NULL)
1908 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 flags.cf_flags = 0;
1911 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1912 if (mod == NULL) {
1913 PyArena_Free(arena);
1914 return NULL;
1915 }
1916 st = PySymtable_Build(mod, filename, 0);
1917 PyArena_Free(arena);
1918 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001919}
1920
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921/* Preferred access to parser is through AST. */
1922mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001923PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 mod_ty mod;
1927 PyCompilerFlags localflags;
1928 perrdetail err;
1929 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1932 &_PyParser_Grammar, start, &err,
1933 &iflags);
1934 if (flags == NULL) {
1935 localflags.cf_flags = 0;
1936 flags = &localflags;
1937 }
1938 if (n) {
1939 flags->cf_flags |= iflags & PyCF_MASK;
1940 mod = PyAST_FromNode(n, flags, filename, arena);
1941 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 }
1943 else {
1944 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001945 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001947 err_free(&err);
1948 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001949}
1950
1951mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001952PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 int start, char *ps1,
1954 char *ps2, PyCompilerFlags *flags, int *errcode,
1955 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 mod_ty mod;
1958 PyCompilerFlags localflags;
1959 perrdetail err;
1960 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1963 &_PyParser_Grammar,
1964 start, ps1, ps2, &err, &iflags);
1965 if (flags == NULL) {
1966 localflags.cf_flags = 0;
1967 flags = &localflags;
1968 }
1969 if (n) {
1970 flags->cf_flags |= iflags & PyCF_MASK;
1971 mod = PyAST_FromNode(n, flags, filename, arena);
1972 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 }
1974 else {
1975 err_input(&err);
1976 if (errcode)
1977 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02001978 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001980 err_free(&err);
1981 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001982}
1983
Guido van Rossuma110aa61994-08-29 12:50:44 +00001984/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001985
Guido van Rossuma110aa61994-08-29 12:50:44 +00001986node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001987PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 perrdetail err;
1990 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1991 &_PyParser_Grammar,
1992 start, NULL, NULL, &err, flags);
1993 if (n == NULL)
1994 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001995 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001998}
1999
Guido van Rossuma110aa61994-08-29 12:50:44 +00002000/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002001
Guido van Rossuma110aa61994-08-29 12:50:44 +00002002node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002003PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 perrdetail err;
2006 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2007 start, &err, flags);
2008 if (n == NULL)
2009 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002010 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002012}
2013
2014node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002015PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 perrdetail err;
2019 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2020 &_PyParser_Grammar, start, &err, flags);
2021 if (n == NULL)
2022 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002023 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002025}
2026
2027node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002028PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002031}
2032
Guido van Rossum66ebd912003-04-17 16:02:26 +00002033/* May want to move a more generalized form of this to parsetok.c or
2034 even parser modules. */
2035
2036void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002037PyParser_ClearError(perrdetail *err)
2038{
2039 err_free(err);
2040}
2041
2042void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002043PyParser_SetError(perrdetail *err)
2044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002046}
2047
Victor Stinner7f2fee32011-04-05 00:39:01 +02002048static void
2049err_free(perrdetail *err)
2050{
2051 Py_CLEAR(err->filename);
2052}
2053
Guido van Rossuma110aa61994-08-29 12:50:44 +00002054/* Set the error appropriate to the given input error code (see errcode.h) */
2055
2056static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002057err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 PyObject *v, *w, *errtype, *errtext;
2060 PyObject *msg_obj = NULL;
2061 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 errtype = PyExc_SyntaxError;
2064 switch (err->error) {
2065 case E_ERROR:
2066 return;
2067 case E_SYNTAX:
2068 errtype = PyExc_IndentationError;
2069 if (err->expected == INDENT)
2070 msg = "expected an indented block";
2071 else if (err->token == INDENT)
2072 msg = "unexpected indent";
2073 else if (err->token == DEDENT)
2074 msg = "unexpected unindent";
2075 else {
2076 errtype = PyExc_SyntaxError;
2077 msg = "invalid syntax";
2078 }
2079 break;
2080 case E_TOKEN:
2081 msg = "invalid token";
2082 break;
2083 case E_EOFS:
2084 msg = "EOF while scanning triple-quoted string literal";
2085 break;
2086 case E_EOLS:
2087 msg = "EOL while scanning string literal";
2088 break;
2089 case E_INTR:
2090 if (!PyErr_Occurred())
2091 PyErr_SetNone(PyExc_KeyboardInterrupt);
2092 goto cleanup;
2093 case E_NOMEM:
2094 PyErr_NoMemory();
2095 goto cleanup;
2096 case E_EOF:
2097 msg = "unexpected EOF while parsing";
2098 break;
2099 case E_TABSPACE:
2100 errtype = PyExc_TabError;
2101 msg = "inconsistent use of tabs and spaces in indentation";
2102 break;
2103 case E_OVERFLOW:
2104 msg = "expression too long";
2105 break;
2106 case E_DEDENT:
2107 errtype = PyExc_IndentationError;
2108 msg = "unindent does not match any outer indentation level";
2109 break;
2110 case E_TOODEEP:
2111 errtype = PyExc_IndentationError;
2112 msg = "too many levels of indentation";
2113 break;
2114 case E_DECODE: {
2115 PyObject *type, *value, *tb;
2116 PyErr_Fetch(&type, &value, &tb);
2117 msg = "unknown decode error";
2118 if (value != NULL)
2119 msg_obj = PyObject_Str(value);
2120 Py_XDECREF(type);
2121 Py_XDECREF(value);
2122 Py_XDECREF(tb);
2123 break;
2124 }
2125 case E_LINECONT:
2126 msg = "unexpected character after line continuation character";
2127 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 case E_IDENTIFIER:
2130 msg = "invalid character in identifier";
2131 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002132 case E_BADSINGLE:
2133 msg = "multiple statements found while compiling a single statement";
2134 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 default:
2136 fprintf(stderr, "error=%d\n", err->error);
2137 msg = "unknown parsing error";
2138 break;
2139 }
2140 /* err->text may not be UTF-8 in case of decoding errors.
2141 Explicitly convert to an object. */
2142 if (!err->text) {
2143 errtext = Py_None;
2144 Py_INCREF(Py_None);
2145 } else {
2146 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2147 "replace");
2148 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002149 v = Py_BuildValue("(OiiN)", err->filename,
2150 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 if (v != NULL) {
2152 if (msg_obj)
2153 w = Py_BuildValue("(OO)", msg_obj, v);
2154 else
2155 w = Py_BuildValue("(sO)", msg, v);
2156 } else
2157 w = NULL;
2158 Py_XDECREF(v);
2159 PyErr_SetObject(errtype, w);
2160 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002161cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 Py_XDECREF(msg_obj);
2163 if (err->text != NULL) {
2164 PyObject_FREE(err->text);
2165 err->text = NULL;
2166 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002167}
2168
2169/* Print fatal error message and abort */
2170
2171void
Tim Peters7c321a82002-07-09 02:57:01 +00002172Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002173{
Victor Stinner024e37a2011-03-31 01:31:06 +02002174 const int fd = fileno(stderr);
2175 PyThreadState *tstate;
2176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 fprintf(stderr, "Fatal Python error: %s\n", msg);
2178 fflush(stderr); /* it helps in Windows debug build */
2179 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002180 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002182 else {
2183 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2184 if (tstate != NULL) {
2185 fputc('\n', stderr);
2186 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002187 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002188 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002189 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002190 }
2191
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002192#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 {
2194 size_t len = strlen(msg);
2195 WCHAR* buffer;
2196 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 /* Convert the message to wchar_t. This uses a simple one-to-one
2199 conversion, assuming that the this error message actually uses ASCII
2200 only. If this ceases to be true, we will have to convert. */
2201 buffer = alloca( (len+1) * (sizeof *buffer));
2202 for( i=0; i<=len; ++i)
2203 buffer[i] = msg[i];
2204 OutputDebugStringW(L"Fatal Python error: ");
2205 OutputDebugStringW(buffer);
2206 OutputDebugStringW(L"\n");
2207 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002208#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002210#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002211#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002213}
2214
2215/* Clean up and exit */
2216
Guido van Rossuma110aa61994-08-29 12:50:44 +00002217#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002218#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002219#endif
2220
Collin Winter670e6922007-03-21 02:57:17 +00002221static void (*pyexitfunc)(void) = NULL;
2222/* For the atexit module. */
2223void _Py_PyAtExit(void (*func)(void))
2224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002226}
2227
2228static void
2229call_py_exitfuncs(void)
2230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 if (pyexitfunc == NULL)
2232 return;
Collin Winter670e6922007-03-21 02:57:17 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 (*pyexitfunc)();
2235 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002236}
2237
Antoine Pitrou011bd622009-10-20 21:52:47 +00002238/* Wait until threading._shutdown completes, provided
2239 the threading module was imported in the first place.
2240 The shutdown routine will wait until all non-daemon
2241 "threading" threads have completed. */
2242static void
2243wait_for_thread_shutdown(void)
2244{
2245#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002246 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 PyObject *result;
2248 PyThreadState *tstate = PyThreadState_GET();
2249 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2250 "threading");
2251 if (threading == NULL) {
2252 /* threading not imported */
2253 PyErr_Clear();
2254 return;
2255 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002256 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 if (result == NULL) {
2258 PyErr_WriteUnraisable(threading);
2259 }
2260 else {
2261 Py_DECREF(result);
2262 }
2263 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002264#endif
2265}
2266
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002267#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002268static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002269static int nexitfuncs = 0;
2270
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002271int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if (nexitfuncs >= NEXITFUNCS)
2274 return -1;
2275 exitfuncs[nexitfuncs++] = func;
2276 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002277}
2278
Guido van Rossumcc283f51997-08-05 02:22:03 +00002279static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002280call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 while (nexitfuncs > 0)
2283 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 fflush(stdout);
2286 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002287}
2288
2289void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002290Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002295}
2296
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002297static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002298initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002299{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002300#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002302#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002303#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002305#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002306#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002308#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002310}
2311
Guido van Rossum7433b121997-02-14 19:45:36 +00002312
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002313/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2314 *
2315 * All of the code in this function must only use async-signal-safe functions,
2316 * listed at `man 7 signal` or
2317 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2318 */
2319void
2320_Py_RestoreSignals(void)
2321{
2322#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002324#endif
2325#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002327#endif
2328#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002330#endif
2331}
2332
2333
Guido van Rossum7433b121997-02-14 19:45:36 +00002334/*
2335 * The file descriptor fd is considered ``interactive'' if either
2336 * a) isatty(fd) is TRUE, or
2337 * b) the -i flag was given, and the filename associated with
2338 * the descriptor is NULL or "<stdin>" or "???".
2339 */
2340int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002341Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 if (isatty((int)fileno(fp)))
2344 return 1;
2345 if (!Py_InteractiveFlag)
2346 return 0;
2347 return (filename == NULL) ||
2348 (strcmp(filename, "<stdin>") == 0) ||
2349 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002350}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002351
2352
Tim Petersd08e3822003-04-17 15:24:21 +00002353#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002354#if defined(WIN32) && defined(_MSC_VER)
2355
2356/* Stack checking for Microsoft C */
2357
2358#include <malloc.h>
2359#include <excpt.h>
2360
Fred Drakee8de31c2000-08-31 05:38:39 +00002361/*
2362 * Return non-zero when we run out of memory on the stack; zero otherwise.
2363 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002364int
Fred Drake399739f2000-08-31 05:52:44 +00002365PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 __try {
2368 /* alloca throws a stack overflow exception if there's
2369 not enough space left on the stack */
2370 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2371 return 0;
2372 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2373 EXCEPTION_EXECUTE_HANDLER :
2374 EXCEPTION_CONTINUE_SEARCH) {
2375 int errcode = _resetstkoflw();
2376 if (errcode == 0)
2377 {
2378 Py_FatalError("Could not reset the stack!");
2379 }
2380 }
2381 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002382}
2383
2384#endif /* WIN32 && _MSC_VER */
2385
2386/* Alternate implementations can be added here... */
2387
2388#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002389
2390
2391/* Wrappers around sigaction() or signal(). */
2392
2393PyOS_sighandler_t
2394PyOS_getsig(int sig)
2395{
2396#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 struct sigaction context;
2398 if (sigaction(sig, NULL, &context) == -1)
2399 return SIG_ERR;
2400 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002401#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002403/* Special signal handling for the secure CRT in Visual Studio 2005 */
2404#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 switch (sig) {
2406 /* Only these signals are valid */
2407 case SIGINT:
2408 case SIGILL:
2409 case SIGFPE:
2410 case SIGSEGV:
2411 case SIGTERM:
2412 case SIGBREAK:
2413 case SIGABRT:
2414 break;
2415 /* Don't call signal() with other values or it will assert */
2416 default:
2417 return SIG_ERR;
2418 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002419#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 handler = signal(sig, SIG_IGN);
2421 if (handler != SIG_ERR)
2422 signal(sig, handler);
2423 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002424#endif
2425}
2426
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002427/*
2428 * All of the code in this function must only use async-signal-safe functions,
2429 * listed at `man 7 signal` or
2430 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2431 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002432PyOS_sighandler_t
2433PyOS_setsig(int sig, PyOS_sighandler_t handler)
2434{
2435#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 /* Some code in Modules/signalmodule.c depends on sigaction() being
2437 * used here if HAVE_SIGACTION is defined. Fix that if this code
2438 * changes to invalidate that assumption.
2439 */
2440 struct sigaction context, ocontext;
2441 context.sa_handler = handler;
2442 sigemptyset(&context.sa_mask);
2443 context.sa_flags = 0;
2444 if (sigaction(sig, &context, &ocontext) == -1)
2445 return SIG_ERR;
2446 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002447#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 PyOS_sighandler_t oldhandler;
2449 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002450#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002452#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002454#endif
2455}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002456
2457/* Deprecated C API functions still provided for binary compatiblity */
2458
2459#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002460PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002461PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002464}
2465
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002466#undef PyParser_SimpleParseString
2467PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002468PyParser_SimpleParseString(const char *str, int start)
2469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002471}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002472
2473#undef PyRun_AnyFile
2474PyAPI_FUNC(int)
2475PyRun_AnyFile(FILE *fp, const char *name)
2476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002478}
2479
2480#undef PyRun_AnyFileEx
2481PyAPI_FUNC(int)
2482PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002485}
2486
2487#undef PyRun_AnyFileFlags
2488PyAPI_FUNC(int)
2489PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002492}
2493
2494#undef PyRun_File
2495PyAPI_FUNC(PyObject *)
2496PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002499}
2500
2501#undef PyRun_FileEx
2502PyAPI_FUNC(PyObject *)
2503PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002506}
2507
2508#undef PyRun_FileFlags
2509PyAPI_FUNC(PyObject *)
2510PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002514}
2515
2516#undef PyRun_SimpleFile
2517PyAPI_FUNC(int)
2518PyRun_SimpleFile(FILE *f, const char *p)
2519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002521}
2522
2523#undef PyRun_SimpleFileEx
2524PyAPI_FUNC(int)
2525PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002528}
2529
2530
2531#undef PyRun_String
2532PyAPI_FUNC(PyObject *)
2533PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002536}
2537
2538#undef PyRun_SimpleString
2539PyAPI_FUNC(int)
2540PyRun_SimpleString(const char *s)
2541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002542 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002543}
2544
2545#undef Py_CompileString
2546PyAPI_FUNC(PyObject *)
2547Py_CompileString(const char *str, const char *p, int s)
2548{
Georg Brandl8334fd92010-12-04 10:26:46 +00002549 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2550}
2551
2552#undef Py_CompileStringFlags
2553PyAPI_FUNC(PyObject *)
2554Py_CompileStringFlags(const char *str, const char *p, int s,
2555 PyCompilerFlags *flags)
2556{
2557 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002558}
2559
2560#undef PyRun_InteractiveOne
2561PyAPI_FUNC(int)
2562PyRun_InteractiveOne(FILE *f, const char *p)
2563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002565}
2566
2567#undef PyRun_InteractiveLoop
2568PyAPI_FUNC(int)
2569PyRun_InteractiveLoop(FILE *f, const char *p)
2570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002572}
2573
2574#ifdef __cplusplus
2575}
2576#endif