blob: 44a85bb355914a8b6d968453dc770ca4ad8ed243 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
43 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#endif
45
46#ifdef __cplusplus
47extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000048#endif
49
Martin v. Löwis790465f2008-04-05 20:41:37 +000050extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000051
Guido van Rossum82598051997-03-05 00:20:32 +000052extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossumb73cc041993-11-01 16:28:59 +000054/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static void initmain(void);
Victor Stinner793b5312011-04-27 00:24:21 +020056static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020065static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000067static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000068static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000069static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +020070extern int _PyUnicode_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000071extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020074extern int _PyFaulthandler_Init(void);
75extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000084int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000085int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020086int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000087int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000088int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000089int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000090int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000091int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000092int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000094int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +010095int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000096
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020097PyThreadState *_Py_Finalizing = NULL;
98
Christian Heimes33fe8092008-04-13 13:53:33 +000099/* PyModule_GetWarningsModule is no longer necessary as of 2.6
100since _warnings is builtin. This API should not be used. */
101PyObject *
102PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000105}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000106
Guido van Rossum25ce5661997-08-02 03:10:38 +0000107static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000108
Thomas Wouters7e474022000-07-16 12:04:32 +0000109/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000110
111int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000112Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000115}
116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117/* Global initializations. Can be undone by Py_Finalize(). Don't
118 call this twice without an intervening Py_Finalize() call. When
119 initializations fail, a fatal error is issued and the function does
120 not return. On return, the first thread and interpreter state have
121 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123 Locking: you must hold the interpreter lock while calling this.
124 (If the lock has not yet been initialized, that's equivalent to
125 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000126
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000128
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000129static int
130add_flag(int flag, const char *envs)
131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int env = atoi(envs);
133 if (flag < env)
134 flag = env;
135 if (flag < 1)
136 flag = 1;
137 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000138}
139
Christian Heimes5833a2f2008-10-30 21:40:04 +0000140static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000141get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000142{
Victor Stinner94908bb2010-08-18 21:23:25 +0000143 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000144 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200145 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000146
Victor Stinner94908bb2010-08-18 21:23:25 +0000147 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (!codec)
149 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000150
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200151 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 Py_CLEAR(codec);
153 if (!name)
154 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000155
Victor Stinner94908bb2010-08-18 21:23:25 +0000156 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100157 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000158 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000159 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000161 if (name_str == NULL) {
162 PyErr_NoMemory();
163 return NULL;
164 }
165 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000166
167error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000169 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000171}
Victor Stinner94908bb2010-08-18 21:23:25 +0000172
Victor Stinner94908bb2010-08-18 21:23:25 +0000173static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200174get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000175{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200176#ifdef MS_WINDOWS
177 char codepage[100];
178 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
179 return get_codec_name(codepage);
180#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000181 char* codeset = nl_langinfo(CODESET);
182 if (!codeset || codeset[0] == '\0') {
183 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
184 return NULL;
185 }
186 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200187#else
188 PyErr_SetNone(PyExc_NotImplementedError);
189 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000190#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200191}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000192
Brett Cannonfd074152012-04-14 14:10:13 -0400193static void
194import_init(PyInterpreterState *interp, PyObject *sysmod)
195{
196 PyObject *importlib;
197 PyObject *impmod;
198 PyObject *sys_modules;
199 PyObject *value;
200
201 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400202 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
203 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
204 }
205 else if (Py_VerboseFlag) {
206 PySys_FormatStderr("import _frozen_importlib # frozen\n");
207 }
208 importlib = PyImport_AddModule("_frozen_importlib");
209 if (importlib == NULL) {
210 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
211 "sys.modules");
212 }
213 interp->importlib = importlib;
214 Py_INCREF(interp->importlib);
215
216 /* Install _importlib as __import__ */
217 impmod = PyInit_imp();
218 if (impmod == NULL) {
219 Py_FatalError("Py_Initialize: can't import imp");
220 }
221 else if (Py_VerboseFlag) {
222 PySys_FormatStderr("import imp # builtin\n");
223 }
224 sys_modules = PyImport_GetModuleDict();
225 if (Py_VerboseFlag) {
226 PySys_FormatStderr("import sys # builtin\n");
227 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400228 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
229 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400230 }
231
232 value = PyObject_CallMethod(importlib, "_setup", "OO", sysmod, impmod);
233 if (value == NULL) {
234 PyErr_Print();
235 Py_FatalError("Py_Initialize: importlib install failed");
236 }
237 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400238 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400239
240 _PyImportZip_Init();
241}
242
243
Guido van Rossuma027efa1997-05-05 20:56:21 +0000244void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000245Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyInterpreterState *interp;
248 PyThreadState *tstate;
249 PyObject *bimod, *sysmod, *pstderr;
250 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (initialized)
254 return;
255 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200256 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000257
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000258#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 /* Set up the LC_CTYPE locale, so we can obtain
260 the locale's charset without having to switch
261 locales. */
262 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000263#endif
264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
266 Py_DebugFlag = add_flag(Py_DebugFlag, p);
267 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
268 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
269 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
270 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
271 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
272 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100273 /* The variable is only tested for existence here; _PyRandom_Init will
274 check its value further. */
275 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
276 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
277
278 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 interp = PyInterpreterState_New();
281 if (interp == NULL)
282 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 tstate = PyThreadState_New(interp);
285 if (tstate == NULL)
286 Py_FatalError("Py_Initialize: can't make first thread");
287 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000288
Victor Stinner6961bd62010-08-17 22:26:51 +0000289#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000290 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
291 destroying the GIL might fail when it is being referenced from
292 another running thread (see issue #9901).
293 Instead we destroy the previously created GIL here, which ensures
294 that we can call Py_Initialize / Py_Finalize multiple times. */
295 _PyEval_FiniThreads();
296
297 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000298 _PyGILState_Init(interp, tstate);
299#endif /* WITH_THREAD */
300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (!_PyFrame_Init())
304 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (!_PyLong_Init())
307 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (!PyByteArray_Init())
310 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 interp->modules = PyDict_New();
315 if (interp->modules == NULL)
316 Py_FatalError("Py_Initialize: can't make modules dictionary");
317 interp->modules_reloading = PyDict_New();
318 if (interp->modules_reloading == NULL)
319 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200322 if (_PyUnicode_Init() < 0)
323 Py_FatalError("Py_Initialize: can't initialize unicode");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 bimod = _PyBuiltin_Init();
326 if (bimod == NULL)
327 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000328 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 interp->builtins = PyModule_GetDict(bimod);
330 if (interp->builtins == NULL)
331 Py_FatalError("Py_Initialize: can't initialize builtins dict");
332 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400335 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 sysmod = _PySys_Init();
338 if (sysmod == NULL)
339 Py_FatalError("Py_Initialize: can't initialize sys");
340 interp->sysdict = PyModule_GetDict(sysmod);
341 if (interp->sysdict == NULL)
342 Py_FatalError("Py_Initialize: can't initialize sys dict");
343 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000344 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 PySys_SetPath(Py_GetPath());
346 PyDict_SetItemString(interp->sysdict, "modules",
347 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 /* Set up a preliminary stderr printer until we have enough
350 infrastructure for the io module in place. */
351 pstderr = PyFile_NewStdPrinter(fileno(stderr));
352 if (pstderr == NULL)
353 Py_FatalError("Py_Initialize: can't set preliminary stderr");
354 PySys_SetObject("stderr", pstderr);
355 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000356 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000361
Victor Stinner024e37a2011-03-31 01:31:06 +0200362 /* initialize the faulthandler module */
363 if (_PyFaulthandler_Init())
364 Py_FatalError("Py_Initialize: can't initialize faulthandler");
365
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000366 /* Initialize _warnings. */
367 _PyWarnings_Init();
368
Brett Cannonfd074152012-04-14 14:10:13 -0400369 import_init(interp, sysmod);
370
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000371 _PyTime_Init();
372
Victor Stinner793b5312011-04-27 00:24:21 +0200373 if (initfsencoding(interp) < 0)
374 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 if (install_sigs)
377 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 initmain(); /* Module __main__ */
380 if (initstdio() < 0)
381 Py_FatalError(
382 "Py_Initialize: can't initialize sys standard streams");
383
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000384 /* Initialize warnings. */
385 if (PySys_HasWarnOptions()) {
386 PyObject *warnings_module = PyImport_ImportModule("warnings");
387 if (warnings_module == NULL) {
388 fprintf(stderr, "'import warnings' failed; traceback:\n");
389 PyErr_Print();
390 }
391 Py_XDECREF(warnings_module);
392 }
393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (!Py_NoSiteFlag)
395 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000396}
397
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000398void
399Py_Initialize(void)
400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000402}
403
404
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000405#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000406extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000407#endif
408
Guido van Rossume8432ac2007-07-09 15:04:50 +0000409/* Flush stdout and stderr */
410
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100411static int
412file_is_closed(PyObject *fobj)
413{
414 int r;
415 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
416 if (tmp == NULL) {
417 PyErr_Clear();
418 return 0;
419 }
420 r = PyObject_IsTrue(tmp);
421 Py_DECREF(tmp);
422 if (r < 0)
423 PyErr_Clear();
424 return r > 0;
425}
426
Neal Norwitz2bad9702007-08-27 06:19:22 +0000427static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000428flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PyObject *fout = PySys_GetObject("stdout");
431 PyObject *ferr = PySys_GetObject("stderr");
432 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200433 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000434
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100435 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200436 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000438 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 else
440 Py_DECREF(tmp);
441 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000442
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100443 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200444 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (tmp == NULL)
446 PyErr_Clear();
447 else
448 Py_DECREF(tmp);
449 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000450}
451
Guido van Rossum25ce5661997-08-02 03:10:38 +0000452/* Undo the effect of Py_Initialize().
453
454 Beware: if multiple interpreter and/or thread states exist, these
455 are not wiped out; only the current thread and interpreter state
456 are deleted. But since everything else is deleted, those other
457 interpreter and thread states should no longer be used.
458
459 (XXX We should do better, e.g. wipe out all interpreters and
460 threads.)
461
462 Locking: as above.
463
464*/
465
466void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000467Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 PyInterpreterState *interp;
470 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (!initialized)
473 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 /* The interpreter is still entirely intact at this point, and the
478 * exit funcs may be relying on that. In particular, if some thread
479 * or exit func is still waiting to do an import, the import machinery
480 * expects Py_IsInitialized() to return true. So don't say the
481 * interpreter is uninitialized until after the exit funcs have run.
482 * Note that Threading.py uses an exit func to do a join on all the
483 * threads created thru it, so this also protects pending imports in
484 * the threads created via Threading.
485 */
486 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 /* Get current thread state and interpreter pointer */
489 tstate = PyThreadState_GET();
490 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000491
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200492 /* Remaining threads (e.g. daemon threads) will automatically exit
493 after taking the GIL (in PyEval_RestoreThread()). */
494 _Py_Finalizing = tstate;
495 initialized = 0;
496
497 /* Flush stdout+stderr */
498 flush_std_files();
499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* Disable signal handling */
501 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* Clear type lookup cache */
504 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 /* Collect garbage. This may call finalizers; it's nice to call these
507 * before all modules are destroyed.
508 * XXX If a __del__ or weakref callback is triggered here, and tries to
509 * XXX import a module, bad things can happen, because Python no
510 * XXX longer believes it's initialized.
511 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
512 * XXX is easy to provoke that way. I've also seen, e.g.,
513 * XXX Exception exceptions.ImportError: 'No module named sha'
514 * XXX in <function callback at 0x008F5718> ignored
515 * XXX but I'm unclear on exactly how that one happens. In any case,
516 * XXX I haven't seen a real-life report of either of these.
517 */
518 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000519#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 /* With COUNT_ALLOCS, it helps to run GC multiple times:
521 each collection might release some types from the type
522 list, so they become garbage. */
523 while (PyGC_Collect() > 0)
524 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000525#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000526 /* We run this while most interpreter state is still alive, so that
527 debug information can be printed out */
528 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 /* Destroy all modules */
531 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 /* Flush stdout+stderr (again, in case more was printed) */
534 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100537 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 * XXX This is disabled because it caused too many problems. If
539 * XXX a __del__ or weakref callback triggers here, Python code has
540 * XXX a hard time running, because even the sys module has been
541 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
542 * XXX One symptom is a sequence of information-free messages
543 * XXX coming from threads (if a __del__ or callback is invoked,
544 * XXX other threads can execute too, and any exception they encounter
545 * XXX triggers a comedy of errors as subsystem after subsystem
546 * XXX fails to find what it *expects* to find in sys to help report
547 * XXX the exception and consequent unexpected failures). I've also
548 * XXX seen segfaults then, after adding print statements to the
549 * XXX Python code getting called.
550 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000551#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000553#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
556 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000557
Victor Stinner024e37a2011-03-31 01:31:06 +0200558 /* unload faulthandler module */
559 _PyFaulthandler_Fini();
560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000562#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000564#endif
565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000567
Tim Peters9cf25ce2003-04-17 15:21:01 +0000568#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 /* Display all objects still alive -- this can invoke arbitrary
570 * __repr__ overrides, so requires a mostly-intact interpreter.
571 * Alas, a lot of stuff may still be alive now that will be cleaned
572 * up later.
573 */
574 if (Py_GETENV("PYTHONDUMPREFS"))
575 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000576#endif /* Py_TRACE_REFS */
577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* Clear interpreter state */
579 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 /* Now we decref the exception classes. After this point nothing
582 can raise an exception. That's okay, because each Fini() method
583 below has been checked to make sure no exceptions are ever
584 raised.
585 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000590#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000592#endif /* WITH_THREAD */
593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 /* Delete current thread */
595 PyThreadState_Swap(NULL);
596 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 /* Sundry finalizers */
599 PyMethod_Fini();
600 PyFrame_Fini();
601 PyCFunction_Fini();
602 PyTuple_Fini();
603 PyList_Fini();
604 PySet_Fini();
605 PyBytes_Fini();
606 PyByteArray_Fini();
607 PyLong_Fini();
608 PyFloat_Fini();
609 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100610 PySlice_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* Cleanup Unicode implementation */
613 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000616 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 free((char*)Py_FileSystemDefaultEncoding);
618 Py_FileSystemDefaultEncoding = NULL;
619 }
Christian Heimesc8967002007-11-30 10:18:26 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 /* XXX Still allocated:
622 - various static ad-hoc pointers to interned strings
623 - int and float free list blocks
624 - whatever various modules and libraries allocate
625 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000628
Tim Peters269b2a62003-04-17 19:52:29 +0000629#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 /* Display addresses (& refcnts) of all objects still alive.
631 * An address can be used to find the repr of the object, printed
632 * above by _Py_PrintReferences.
633 */
634 if (Py_GETENV("PYTHONDUMPREFS"))
635 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000636#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000637#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 if (Py_GETENV("PYTHONMALLOCSTATS"))
639 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000640#endif
641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000643}
644
645/* Create and initialize a new interpreter and thread, and return the
646 new thread. This requires that Py_Initialize() has been called
647 first.
648
649 Unsuccessful initialization yields a NULL pointer. Note that *no*
650 exception information is available even in this case -- the
651 exception information is held in the thread, and there is no
652 thread.
653
654 Locking: as above.
655
656*/
657
658PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000659Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyInterpreterState *interp;
662 PyThreadState *tstate, *save_tstate;
663 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (!initialized)
666 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 interp = PyInterpreterState_New();
669 if (interp == NULL)
670 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 tstate = PyThreadState_New(interp);
673 if (tstate == NULL) {
674 PyInterpreterState_Delete(interp);
675 return NULL;
676 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 interp->modules = PyDict_New();
683 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000684
Victor Stinner49d3f252010-10-17 01:24:53 +0000685 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 if (bimod != NULL) {
687 interp->builtins = PyModule_GetDict(bimod);
688 if (interp->builtins == NULL)
689 goto handle_error;
690 Py_INCREF(interp->builtins);
691 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400694 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000695
Victor Stinner49d3f252010-10-17 01:24:53 +0000696 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (bimod != NULL && sysmod != NULL) {
698 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 interp->sysdict = PyModule_GetDict(sysmod);
701 if (interp->sysdict == NULL)
702 goto handle_error;
703 Py_INCREF(interp->sysdict);
704 PySys_SetPath(Py_GetPath());
705 PyDict_SetItemString(interp->sysdict, "modules",
706 interp->modules);
707 /* Set up a preliminary stderr printer until we have enough
708 infrastructure for the io module in place. */
709 pstderr = PyFile_NewStdPrinter(fileno(stderr));
710 if (pstderr == NULL)
711 Py_FatalError("Py_Initialize: can't set preliminary stderr");
712 PySys_SetObject("stderr", pstderr);
713 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000714 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200717
Brett Cannonfd074152012-04-14 14:10:13 -0400718 import_init(interp, sysmod);
719
Victor Stinner793b5312011-04-27 00:24:21 +0200720 if (initfsencoding(interp) < 0)
721 goto handle_error;
722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 if (initstdio() < 0)
724 Py_FatalError(
725 "Py_Initialize: can't initialize sys standard streams");
726 initmain();
727 if (!Py_NoSiteFlag)
728 initsite();
729 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (!PyErr_Occurred())
732 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000733
Thomas Wouters89f507f2006-12-13 04:49:30 +0000734handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000736
Victor Stinnerc40a3502011-04-27 00:20:27 +0200737 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 PyThreadState_Clear(tstate);
739 PyThreadState_Swap(save_tstate);
740 PyThreadState_Delete(tstate);
741 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000744}
745
746/* Delete an interpreter and its last thread. This requires that the
747 given thread state is current, that the thread has no remaining
748 frames, and that it is its interpreter's only remaining thread.
749 It is a fatal error to violate these constraints.
750
751 (Py_Finalize() doesn't have these constraints -- it zaps
752 everything, regardless.)
753
754 Locking: as above.
755
756*/
757
758void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000759Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 if (tstate != PyThreadState_GET())
764 Py_FatalError("Py_EndInterpreter: thread is not current");
765 if (tstate->frame != NULL)
766 Py_FatalError("Py_EndInterpreter: thread still has a frame");
767 if (tstate != interp->tstate_head || tstate->next != NULL)
768 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 PyImport_Cleanup();
771 PyInterpreterState_Clear(interp);
772 PyThreadState_Swap(NULL);
773 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000774}
775
Martin v. Löwis790465f2008-04-05 20:41:37 +0000776static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000777
778void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000779Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (pn && *pn)
782 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000783}
784
Martin v. Löwis790465f2008-04-05 20:41:37 +0000785wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000786Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000789}
790
Martin v. Löwis790465f2008-04-05 20:41:37 +0000791static wchar_t *default_home = NULL;
792static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000793
794void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000795Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000798}
799
Martin v. Löwis790465f2008-04-05 20:41:37 +0000800wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000801Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 wchar_t *home = default_home;
804 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
805 char* chome = Py_GETENV("PYTHONHOME");
806 if (chome) {
807 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
808 if (r != (size_t)-1 && r <= PATH_MAX)
809 home = env_home;
810 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 }
813 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000814}
815
Guido van Rossum6135a871995-01-09 17:53:26 +0000816/* Create __main__ module */
817
818static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000819initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyObject *m, *d;
822 m = PyImport_AddModule("__main__");
823 if (m == NULL)
824 Py_FatalError("can't create __main__ module");
825 d = PyModule_GetDict(m);
826 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
827 PyObject *bimod = PyImport_ImportModule("builtins");
828 if (bimod == NULL ||
829 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
830 Py_FatalError("can't add __builtins__ to __main__");
831 Py_DECREF(bimod);
832 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000833}
834
Victor Stinner793b5312011-04-27 00:24:21 +0200835static int
836initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000837{
838 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000839
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200840 if (Py_FileSystemDefaultEncoding == NULL)
841 {
842 Py_FileSystemDefaultEncoding = get_locale_encoding();
843 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000844 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000845
Victor Stinnere4743092010-10-19 00:05:51 +0000846 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200847 interp->fscodec_initialized = 1;
848 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000849 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000850
851 /* the encoding is mbcs, utf-8 or ascii */
852 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
853 if (!codec) {
854 /* Such error can only occurs in critical situations: no more
855 * memory, import a module of the standard library failed,
856 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200857 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000858 }
Victor Stinner793b5312011-04-27 00:24:21 +0200859 Py_DECREF(codec);
860 interp->fscodec_initialized = 1;
861 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000862}
863
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000864/* Import the site module (not into __main__ though) */
865
866static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000867initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyObject *m;
870 m = PyImport_ImportModule("site");
871 if (m == NULL) {
872 PyErr_Print();
873 Py_Finalize();
874 exit(1);
875 }
876 else {
877 Py_DECREF(m);
878 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000879}
880
Antoine Pitrou05608432009-01-09 18:53:14 +0000881static PyObject*
882create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 int fd, int write_mode, char* name,
884 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
887 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000888 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 PyObject *line_buffering;
890 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200891 _Py_IDENTIFIER(open);
892 _Py_IDENTIFIER(isatty);
893 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200894 _Py_IDENTIFIER(name);
895 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 /* stdin is always opened in buffered mode, first because it shouldn't
898 make a difference in common use cases, second because TextIOWrapper
899 depends on the presence of a read1() method which only exists on
900 buffered streams.
901 */
902 if (Py_UnbufferedStdioFlag && write_mode)
903 buffering = 0;
904 else
905 buffering = -1;
906 if (write_mode)
907 mode = "wb";
908 else
909 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200910 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
911 fd, mode, buffering,
912 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (buf == NULL)
914 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200917 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200918 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 if (raw == NULL)
920 goto error;
921 }
922 else {
923 raw = buf;
924 Py_INCREF(raw);
925 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200928 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200930 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 if (res == NULL)
932 goto error;
933 isatty = PyObject_IsTrue(res);
934 Py_DECREF(res);
935 if (isatty == -1)
936 goto error;
937 if (isatty || Py_UnbufferedStdioFlag)
938 line_buffering = Py_True;
939 else
940 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 Py_CLEAR(raw);
943 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000944
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000945 newline = "\n";
946#ifdef MS_WINDOWS
947 if (!write_mode) {
948 /* translate \r\n to \n for sys.stdin on Windows */
949 newline = NULL;
950 }
951#endif
952
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200953 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
954 buf, encoding, errors,
955 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 Py_CLEAR(buf);
957 if (stream == NULL)
958 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 if (write_mode)
961 mode = "w";
962 else
963 mode = "r";
964 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200965 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 goto error;
967 Py_CLEAR(text);
968 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000969
970error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 Py_XDECREF(buf);
972 Py_XDECREF(stream);
973 Py_XDECREF(text);
974 Py_XDECREF(raw);
975 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000976}
977
Antoine Pitrou11942a52011-11-28 19:08:36 +0100978static int
979is_valid_fd(int fd)
980{
981 int dummy_fd;
982 if (fd < 0 || !_PyVerify_fd(fd))
983 return 0;
984 dummy_fd = dup(fd);
985 if (dummy_fd < 0)
986 return 0;
987 close(dummy_fd);
988 return 1;
989}
990
Georg Brandl1a3284e2007-12-02 09:40:06 +0000991/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000992static int
993initstdio(void)
994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 PyObject *iomod = NULL, *wrapper;
996 PyObject *bimod = NULL;
997 PyObject *m;
998 PyObject *std = NULL;
999 int status = 0, fd;
1000 PyObject * encoding_attr;
1001 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 /* Hack to avoid a nasty recursion issue when Python is invoked
1004 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1005 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1006 goto error;
1007 }
1008 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1011 goto error;
1012 }
1013 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (!(bimod = PyImport_ImportModule("builtins"))) {
1016 goto error;
1017 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 if (!(iomod = PyImport_ImportModule("io"))) {
1020 goto error;
1021 }
1022 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1023 goto error;
1024 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 /* Set builtins.open */
1027 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001028 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 goto error;
1030 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001031 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 encoding = Py_GETENV("PYTHONIOENCODING");
1034 errors = NULL;
1035 if (encoding) {
1036 encoding = strdup(encoding);
1037 errors = strchr(encoding, ':');
1038 if (errors) {
1039 *errors = '\0';
1040 errors++;
1041 }
1042 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 /* Set sys.stdin */
1045 fd = fileno(stdin);
1046 /* Under some conditions stdin, stdout and stderr may not be connected
1047 * and fileno() may point to an invalid file descriptor. For example
1048 * GUI apps don't have valid standard streams by default.
1049 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001050 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 std = Py_None;
1052 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 }
1054 else {
1055 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1056 if (std == NULL)
1057 goto error;
1058 } /* if (fd < 0) */
1059 PySys_SetObject("__stdin__", std);
1060 PySys_SetObject("stdin", std);
1061 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 /* Set sys.stdout */
1064 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001065 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 std = Py_None;
1067 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 }
1069 else {
1070 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1071 if (std == NULL)
1072 goto error;
1073 } /* if (fd < 0) */
1074 PySys_SetObject("__stdout__", std);
1075 PySys_SetObject("stdout", std);
1076 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001077
Guido van Rossum98297ee2007-11-06 21:34:58 +00001078#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 /* Set sys.stderr, replaces the preliminary stderr */
1080 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001081 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 std = Py_None;
1083 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 }
1085 else {
1086 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1087 if (std == NULL)
1088 goto error;
1089 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 /* Same as hack above, pre-import stderr's codec to avoid recursion
1092 when import.c tries to write to stderr in verbose mode. */
1093 encoding_attr = PyObject_GetAttrString(std, "encoding");
1094 if (encoding_attr != NULL) {
1095 const char * encoding;
1096 encoding = _PyUnicode_AsString(encoding_attr);
1097 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001098 PyObject *codec_info = _PyCodec_Lookup(encoding);
1099 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001101 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 }
1103 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 PySys_SetObject("__stderr__", std);
1106 PySys_SetObject("stderr", std);
1107 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001108#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001111 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 status = -1;
1113 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (encoding)
1116 free(encoding);
1117 Py_XDECREF(bimod);
1118 Py_XDECREF(iomod);
1119 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001120}
1121
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001122/* Parse input from a file and execute it */
1123
1124int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001125PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 if (filename == NULL)
1129 filename = "???";
1130 if (Py_FdIsInteractive(fp, filename)) {
1131 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1132 if (closeit)
1133 fclose(fp);
1134 return err;
1135 }
1136 else
1137 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001138}
1139
1140int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001141PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyObject *v;
1144 int ret;
1145 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (flags == NULL) {
1148 flags = &local_flags;
1149 local_flags.cf_flags = 0;
1150 }
1151 v = PySys_GetObject("ps1");
1152 if (v == NULL) {
1153 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1154 Py_XDECREF(v);
1155 }
1156 v = PySys_GetObject("ps2");
1157 if (v == NULL) {
1158 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1159 Py_XDECREF(v);
1160 }
1161 for (;;) {
1162 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1163 PRINT_TOTAL_REFS();
1164 if (ret == E_EOF)
1165 return 0;
1166 /*
1167 if (ret == E_NOMEM)
1168 return -1;
1169 */
1170 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001171}
1172
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001173/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001174static int PARSER_FLAGS(PyCompilerFlags *flags)
1175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 int parser_flags = 0;
1177 if (!flags)
1178 return 0;
1179 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1180 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1181 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1182 parser_flags |= PyPARSE_IGNORE_COOKIE;
1183 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1184 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1185 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001186}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001187
Thomas Wouters89f507f2006-12-13 04:49:30 +00001188#if 0
1189/* Keep an example of flags with future keyword support. */
1190#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1192 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1193 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1194 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001195#endif
1196
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001197int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001198PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyObject *m, *d, *v, *w, *oenc = NULL;
1201 mod_ty mod;
1202 PyArena *arena;
1203 char *ps1 = "", *ps2 = "", *enc = NULL;
1204 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001205 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (fp == stdin) {
1208 /* Fetch encoding from sys.stdin */
1209 v = PySys_GetObject("stdin");
1210 if (v == NULL || v == Py_None)
1211 return -1;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001212 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (!oenc)
1214 return -1;
1215 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001216 if (enc == NULL)
1217 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 }
1219 v = PySys_GetObject("ps1");
1220 if (v != NULL) {
1221 v = PyObject_Str(v);
1222 if (v == NULL)
1223 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001224 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001226 if (ps1 == NULL) {
1227 PyErr_Clear();
1228 ps1 = "";
1229 }
1230 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 }
1232 w = PySys_GetObject("ps2");
1233 if (w != NULL) {
1234 w = PyObject_Str(w);
1235 if (w == NULL)
1236 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001237 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001239 if (ps2 == NULL) {
1240 PyErr_Clear();
1241 ps2 = "";
1242 }
1243 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 }
1245 arena = PyArena_New();
1246 if (arena == NULL) {
1247 Py_XDECREF(v);
1248 Py_XDECREF(w);
1249 Py_XDECREF(oenc);
1250 return -1;
1251 }
1252 mod = PyParser_ASTFromFile(fp, filename, enc,
1253 Py_single_input, ps1, ps2,
1254 flags, &errcode, arena);
1255 Py_XDECREF(v);
1256 Py_XDECREF(w);
1257 Py_XDECREF(oenc);
1258 if (mod == NULL) {
1259 PyArena_Free(arena);
1260 if (errcode == E_EOF) {
1261 PyErr_Clear();
1262 return E_EOF;
1263 }
1264 PyErr_Print();
1265 return -1;
1266 }
1267 m = PyImport_AddModule("__main__");
1268 if (m == NULL) {
1269 PyArena_Free(arena);
1270 return -1;
1271 }
1272 d = PyModule_GetDict(m);
1273 v = run_mod(mod, filename, d, d, flags, arena);
1274 PyArena_Free(arena);
1275 flush_io();
1276 if (v == NULL) {
1277 PyErr_Print();
1278 return -1;
1279 }
1280 Py_DECREF(v);
1281 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001282}
1283
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001284/* Check whether a file maybe a pyc file: Look at the extension,
1285 the file type, and, if we may close it, at the first few bytes. */
1286
1287static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001288maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1291 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 /* Only look into the file if we are allowed to close it, since
1294 it then should also be seekable. */
1295 if (closeit) {
1296 /* Read only two bytes of the magic. If the file was opened in
1297 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1298 be read as they are on disk. */
1299 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1300 unsigned char buf[2];
1301 /* Mess: In case of -x, the stream is NOT at its start now,
1302 and ungetc() was used to push back the first newline,
1303 which makes the current stream position formally undefined,
1304 and a x-platform nightmare.
1305 Unfortunately, we have no direct way to know whether -x
1306 was specified. So we use a terrible hack: if the current
1307 stream position is not 0, we assume -x was specified, and
1308 give up. Bug 132850 on SourceForge spells out the
1309 hopelessness of trying anything else (fseek and ftell
1310 don't work predictably x-platform for text-mode files).
1311 */
1312 int ispyc = 0;
1313 if (ftell(fp) == 0) {
1314 if (fread(buf, 1, 2, fp) == 2 &&
1315 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1316 ispyc = 1;
1317 rewind(fp);
1318 }
1319 return ispyc;
1320 }
1321 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001322}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001323
Guido van Rossum0df002c2000-08-27 19:21:52 +00001324int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001325PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 PyObject *m, *d, *v;
1329 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001330 int set_file_name = 0, ret;
1331 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 m = PyImport_AddModule("__main__");
1334 if (m == NULL)
1335 return -1;
1336 d = PyModule_GetDict(m);
1337 if (PyDict_GetItemString(d, "__file__") == NULL) {
1338 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001339 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 if (f == NULL)
1341 return -1;
1342 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1343 Py_DECREF(f);
1344 return -1;
1345 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001346 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1347 Py_DECREF(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 return -1;
Barry Warsaw916048d2011-09-20 14:45:44 -04001349 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 set_file_name = 1;
1351 Py_DECREF(f);
1352 }
1353 len = strlen(filename);
1354 ext = filename + len - (len > 4 ? 4 : 0);
1355 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1356 /* Try to run a pyc file. First, re-open in binary */
1357 if (closeit)
1358 fclose(fp);
1359 if ((fp = fopen(filename, "rb")) == NULL) {
1360 fprintf(stderr, "python: Can't reopen .pyc file\n");
1361 ret = -1;
1362 goto done;
1363 }
1364 /* Turn on optimization if a .pyo file is given */
1365 if (strcmp(ext, ".pyo") == 0)
1366 Py_OptimizeFlag = 1;
1367 v = run_pyc_file(fp, filename, d, d, flags);
1368 } else {
1369 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1370 closeit, flags);
1371 }
1372 flush_io();
1373 if (v == NULL) {
1374 PyErr_Print();
1375 ret = -1;
1376 goto done;
1377 }
1378 Py_DECREF(v);
1379 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001380 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1382 PyErr_Clear();
1383 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001384}
1385
1386int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001387PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyObject *m, *d, *v;
1390 m = PyImport_AddModule("__main__");
1391 if (m == NULL)
1392 return -1;
1393 d = PyModule_GetDict(m);
1394 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1395 if (v == NULL) {
1396 PyErr_Print();
1397 return -1;
1398 }
1399 Py_DECREF(v);
1400 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001401}
1402
Barry Warsaw035574d1997-08-29 22:07:17 +00001403static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001404parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 long hold;
1408 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001409 _Py_IDENTIFIER(msg);
1410 _Py_IDENTIFIER(filename);
1411 _Py_IDENTIFIER(lineno);
1412 _Py_IDENTIFIER(offset);
1413 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001414
Benjamin Peterson80d50422012-04-03 00:30:38 -04001415 *message = NULL;
1416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001418 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001419 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001421
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001422 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001423 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001425 if (v == Py_None) {
1426 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001428 }
1429 else {
1430 *filename = _PyUnicode_AsString(v);
1431 Py_DECREF(v);
1432 if (!*filename)
1433 goto finally;
1434 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001435
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001436 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001437 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 goto finally;
1439 hold = PyLong_AsLong(v);
1440 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 if (hold < 0 && PyErr_Occurred())
1442 goto finally;
1443 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001444
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001445 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001446 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 goto finally;
1448 if (v == Py_None) {
1449 *offset = -1;
1450 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 } else {
1452 hold = PyLong_AsLong(v);
1453 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 if (hold < 0 && PyErr_Occurred())
1455 goto finally;
1456 *offset = (int)hold;
1457 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001458
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001459 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001460 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001462 if (v == Py_None) {
1463 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001465 }
1466 else {
1467 *text = _PyUnicode_AsString(v);
1468 Py_DECREF(v);
1469 if (!*text)
1470 goto finally;
1471 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001473
1474finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001475 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001477}
1478
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001479void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001480PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001483}
1484
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001485static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001486print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 char *nl;
1489 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001490 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1491 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 for (;;) {
1493 nl = strchr(text, '\n');
1494 if (nl == NULL || nl-text >= offset)
1495 break;
1496 offset -= (int)(nl+1-text);
1497 text = nl+1;
1498 }
1499 while (*text == ' ' || *text == '\t') {
1500 text++;
1501 offset--;
1502 }
1503 }
1504 PyFile_WriteString(" ", f);
1505 PyFile_WriteString(text, f);
1506 if (*text == '\0' || text[strlen(text)-1] != '\n')
1507 PyFile_WriteString("\n", f);
1508 if (offset == -1)
1509 return;
1510 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001511 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001514}
1515
Guido van Rossum66e8e862001-03-23 17:54:43 +00001516static void
1517handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 PyObject *exception, *value, *tb;
1520 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (Py_InspectFlag)
1523 /* Don't exit if -i flag was given. This flag is set to 0
1524 * when entering interactive mode for inspecting. */
1525 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 PyErr_Fetch(&exception, &value, &tb);
1528 fflush(stdout);
1529 if (value == NULL || value == Py_None)
1530 goto done;
1531 if (PyExceptionInstance_Check(value)) {
1532 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001533 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001534 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (code) {
1536 Py_DECREF(value);
1537 value = code;
1538 if (value == Py_None)
1539 goto done;
1540 }
1541 /* If we failed to dig out the 'code' attribute,
1542 just let the else clause below print the error. */
1543 }
1544 if (PyLong_Check(value))
1545 exitcode = (int)PyLong_AsLong(value);
1546 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001547 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001548 if (sys_stderr != NULL && sys_stderr != Py_None) {
1549 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1550 } else {
1551 PyObject_Print(value, stderr, Py_PRINT_RAW);
1552 fflush(stderr);
1553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 PySys_WriteStderr("\n");
1555 exitcode = 1;
1556 }
Tim Peterscf615b52003-04-19 18:47:02 +00001557 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 /* Restore and clear the exception info, in order to properly decref
1559 * the exception, value, and traceback. If we just exit instead,
1560 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1561 * some finalizers from running.
1562 */
1563 PyErr_Restore(exception, value, tb);
1564 PyErr_Clear();
1565 Py_Exit(exitcode);
1566 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001567}
1568
1569void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001570PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1575 handle_system_exit();
1576 }
1577 PyErr_Fetch(&exception, &v, &tb);
1578 if (exception == NULL)
1579 return;
1580 PyErr_NormalizeException(&exception, &v, &tb);
1581 if (tb == NULL) {
1582 tb = Py_None;
1583 Py_INCREF(tb);
1584 }
1585 PyException_SetTraceback(v, tb);
1586 if (exception == NULL)
1587 return;
1588 /* Now we know v != NULL too */
1589 if (set_sys_last_vars) {
1590 PySys_SetObject("last_type", exception);
1591 PySys_SetObject("last_value", v);
1592 PySys_SetObject("last_traceback", tb);
1593 }
1594 hook = PySys_GetObject("excepthook");
1595 if (hook) {
1596 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1597 PyObject *result = PyEval_CallObject(hook, args);
1598 if (result == NULL) {
1599 PyObject *exception2, *v2, *tb2;
1600 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1601 handle_system_exit();
1602 }
1603 PyErr_Fetch(&exception2, &v2, &tb2);
1604 PyErr_NormalizeException(&exception2, &v2, &tb2);
1605 /* It should not be possible for exception2 or v2
1606 to be NULL. However PyErr_Display() can't
1607 tolerate NULLs, so just be safe. */
1608 if (exception2 == NULL) {
1609 exception2 = Py_None;
1610 Py_INCREF(exception2);
1611 }
1612 if (v2 == NULL) {
1613 v2 = Py_None;
1614 Py_INCREF(v2);
1615 }
1616 fflush(stdout);
1617 PySys_WriteStderr("Error in sys.excepthook:\n");
1618 PyErr_Display(exception2, v2, tb2);
1619 PySys_WriteStderr("\nOriginal exception was:\n");
1620 PyErr_Display(exception, v, tb);
1621 Py_DECREF(exception2);
1622 Py_DECREF(v2);
1623 Py_XDECREF(tb2);
1624 }
1625 Py_XDECREF(result);
1626 Py_XDECREF(args);
1627 } else {
1628 PySys_WriteStderr("sys.excepthook is missing\n");
1629 PyErr_Display(exception, v, tb);
1630 }
1631 Py_XDECREF(exception);
1632 Py_XDECREF(v);
1633 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001634}
1635
Benjamin Petersone6528212008-07-15 15:32:09 +00001636static void
1637print_exception(PyObject *f, PyObject *value)
1638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 int err = 0;
1640 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001641 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (!PyExceptionInstance_Check(value)) {
1644 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1645 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1646 PyFile_WriteString(" found\n", f);
1647 return;
1648 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 Py_INCREF(value);
1651 fflush(stdout);
1652 type = (PyObject *) Py_TYPE(value);
1653 tb = PyException_GetTraceback(value);
1654 if (tb && tb != Py_None)
1655 err = PyTraceBack_Print(tb, f);
1656 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001657 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 {
1659 PyObject *message;
1660 const char *filename, *text;
1661 int lineno, offset;
1662 if (!parse_syntax_error(value, &message, &filename,
1663 &lineno, &offset, &text))
1664 PyErr_Clear();
1665 else {
1666 char buf[10];
1667 PyFile_WriteString(" File \"", f);
1668 if (filename == NULL)
1669 PyFile_WriteString("<string>", f);
1670 else
1671 PyFile_WriteString(filename, f);
1672 PyFile_WriteString("\", line ", f);
1673 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1674 PyFile_WriteString(buf, f);
1675 PyFile_WriteString("\n", f);
1676 if (text != NULL)
1677 print_error_text(f, offset, text);
1678 Py_DECREF(value);
1679 value = message;
1680 /* Can't be bothered to check all those
1681 PyFile_WriteString() calls */
1682 if (PyErr_Occurred())
1683 err = -1;
1684 }
1685 }
1686 if (err) {
1687 /* Don't do anything else */
1688 }
1689 else {
1690 PyObject* moduleName;
1691 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001692 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 assert(PyExceptionClass_Check(type));
1694 className = PyExceptionClass_Name(type);
1695 if (className != NULL) {
1696 char *dot = strrchr(className, '.');
1697 if (dot != NULL)
1698 className = dot+1;
1699 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001700
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001701 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1703 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001704 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 err = PyFile_WriteString("<unknown>", f);
1706 }
1707 else {
1708 char* modstr = _PyUnicode_AsString(moduleName);
1709 if (modstr && strcmp(modstr, "builtins"))
1710 {
1711 err = PyFile_WriteString(modstr, f);
1712 err += PyFile_WriteString(".", f);
1713 }
1714 Py_DECREF(moduleName);
1715 }
1716 if (err == 0) {
1717 if (className == NULL)
1718 err = PyFile_WriteString("<unknown>", f);
1719 else
1720 err = PyFile_WriteString(className, f);
1721 }
1722 }
1723 if (err == 0 && (value != Py_None)) {
1724 PyObject *s = PyObject_Str(value);
1725 /* only print colon if the str() of the
1726 object is not the empty string
1727 */
1728 if (s == NULL)
1729 err = -1;
1730 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001731 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 err = PyFile_WriteString(": ", f);
1733 if (err == 0)
1734 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1735 Py_XDECREF(s);
1736 }
1737 /* try to write a newline in any case */
1738 err += PyFile_WriteString("\n", f);
1739 Py_XDECREF(tb);
1740 Py_DECREF(value);
1741 /* If an error happened here, don't show it.
1742 XXX This is wrong, but too many callers rely on this behavior. */
1743 if (err != 0)
1744 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001745}
1746
1747static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 "\nThe above exception was the direct cause "
1749 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001750
1751static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 "\nDuring handling of the above exception, "
1753 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001754
1755static void
1756print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 int err = 0, res;
1759 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 if (seen != NULL) {
1762 /* Exception chaining */
1763 if (PySet_Add(seen, value) == -1)
1764 PyErr_Clear();
1765 else if (PyExceptionInstance_Check(value)) {
1766 cause = PyException_GetCause(value);
1767 context = PyException_GetContext(value);
Nick Coghlanab7bf212012-02-26 17:49:52 +10001768 if (cause && cause == Py_None) {
1769 /* print neither cause nor context */
1770 ;
1771 }
1772 else if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 res = PySet_Contains(seen, cause);
1774 if (res == -1)
1775 PyErr_Clear();
1776 if (res == 0) {
1777 print_exception_recursive(
1778 f, cause, seen);
1779 err |= PyFile_WriteString(
1780 cause_message, f);
1781 }
1782 }
1783 else if (context) {
1784 res = PySet_Contains(seen, context);
1785 if (res == -1)
1786 PyErr_Clear();
1787 if (res == 0) {
1788 print_exception_recursive(
1789 f, context, seen);
1790 err |= PyFile_WriteString(
1791 context_message, f);
1792 }
1793 }
1794 Py_XDECREF(context);
1795 Py_XDECREF(cause);
1796 }
1797 }
1798 print_exception(f, value);
1799 if (err != 0)
1800 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001801}
1802
Thomas Wouters477c8d52006-05-27 19:21:47 +00001803void
1804PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 PyObject *seen;
1807 PyObject *f = PySys_GetObject("stderr");
1808 if (f == Py_None) {
1809 /* pass */
1810 }
1811 else if (f == NULL) {
1812 _PyObject_Dump(value);
1813 fprintf(stderr, "lost sys.stderr\n");
1814 }
1815 else {
1816 /* We choose to ignore seen being possibly NULL, and report
1817 at least the main exception (it could be a MemoryError).
1818 */
1819 seen = PySet_New(NULL);
1820 if (seen == NULL)
1821 PyErr_Clear();
1822 print_exception_recursive(f, value, seen);
1823 Py_XDECREF(seen);
1824 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001825}
1826
Guido van Rossum82598051997-03-05 00:20:32 +00001827PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001828PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 PyObject *ret = NULL;
1832 mod_ty mod;
1833 PyArena *arena = PyArena_New();
1834 if (arena == NULL)
1835 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1838 if (mod != NULL)
1839 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1840 PyArena_Free(arena);
1841 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001842}
1843
1844PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001845PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyObject *ret;
1849 mod_ty mod;
1850 PyArena *arena = PyArena_New();
1851 if (arena == NULL)
1852 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1855 flags, NULL, arena);
1856 if (closeit)
1857 fclose(fp);
1858 if (mod == NULL) {
1859 PyArena_Free(arena);
1860 return NULL;
1861 }
1862 ret = run_mod(mod, filename, globals, locals, flags, arena);
1863 PyArena_Free(arena);
1864 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001865}
1866
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001867static void
1868flush_io(void)
1869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 PyObject *f, *r;
1871 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001872 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 /* Save the current exception */
1875 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 f = PySys_GetObject("stderr");
1878 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001879 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (r)
1881 Py_DECREF(r);
1882 else
1883 PyErr_Clear();
1884 }
1885 f = PySys_GetObject("stdout");
1886 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001887 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (r)
1889 Py_DECREF(r);
1890 else
1891 PyErr_Clear();
1892 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001895}
1896
Guido van Rossum82598051997-03-05 00:20:32 +00001897static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 PyCodeObject *co;
1902 PyObject *v;
1903 co = PyAST_Compile(mod, filename, flags, arena);
1904 if (co == NULL)
1905 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001906 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 Py_DECREF(co);
1908 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001909}
1910
Guido van Rossum82598051997-03-05 00:20:32 +00001911static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001912run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 PyCodeObject *co;
1916 PyObject *v;
1917 long magic;
1918 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 magic = PyMarshal_ReadLongFromFile(fp);
1921 if (magic != PyImport_GetMagicNumber()) {
1922 PyErr_SetString(PyExc_RuntimeError,
1923 "Bad magic number in .pyc file");
1924 return NULL;
1925 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001926 /* Skip mtime and size */
1927 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 (void) PyMarshal_ReadLongFromFile(fp);
1929 v = PyMarshal_ReadLastObjectFromFile(fp);
1930 fclose(fp);
1931 if (v == NULL || !PyCode_Check(v)) {
1932 Py_XDECREF(v);
1933 PyErr_SetString(PyExc_RuntimeError,
1934 "Bad code object in .pyc file");
1935 return NULL;
1936 }
1937 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001938 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 if (v && flags)
1940 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1941 Py_DECREF(co);
1942 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001943}
1944
Guido van Rossum82598051997-03-05 00:20:32 +00001945PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001946Py_CompileStringExFlags(const char *str, const char *filename, int start,
1947 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 PyCodeObject *co;
1950 mod_ty mod;
1951 PyArena *arena = PyArena_New();
1952 if (arena == NULL)
1953 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1956 if (mod == NULL) {
1957 PyArena_Free(arena);
1958 return NULL;
1959 }
1960 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1961 PyObject *result = PyAST_mod2obj(mod);
1962 PyArena_Free(arena);
1963 return result;
1964 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001965 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 PyArena_Free(arena);
1967 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001968}
1969
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001970/* For use in Py_LIMITED_API */
1971#undef Py_CompileString
1972PyObject *
1973PyCompileString(const char *str, const char *filename, int start)
1974{
1975 return Py_CompileStringFlags(str, filename, start, NULL);
1976}
1977
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001978struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001979Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 struct symtable *st;
1982 mod_ty mod;
1983 PyCompilerFlags flags;
1984 PyArena *arena = PyArena_New();
1985 if (arena == NULL)
1986 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 flags.cf_flags = 0;
1989 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1990 if (mod == NULL) {
1991 PyArena_Free(arena);
1992 return NULL;
1993 }
1994 st = PySymtable_Build(mod, filename, 0);
1995 PyArena_Free(arena);
1996 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001997}
1998
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999/* Preferred access to parser is through AST. */
2000mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002001PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 mod_ty mod;
2005 PyCompilerFlags localflags;
2006 perrdetail err;
2007 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
2010 &_PyParser_Grammar, start, &err,
2011 &iflags);
2012 if (flags == NULL) {
2013 localflags.cf_flags = 0;
2014 flags = &localflags;
2015 }
2016 if (n) {
2017 flags->cf_flags |= iflags & PyCF_MASK;
2018 mod = PyAST_FromNode(n, flags, filename, arena);
2019 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 }
2021 else {
2022 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002023 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002025 err_free(&err);
2026 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002027}
2028
2029mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00002030PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 int start, char *ps1,
2032 char *ps2, PyCompilerFlags *flags, int *errcode,
2033 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 mod_ty mod;
2036 PyCompilerFlags localflags;
2037 perrdetail err;
2038 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
2041 &_PyParser_Grammar,
2042 start, ps1, ps2, &err, &iflags);
2043 if (flags == NULL) {
2044 localflags.cf_flags = 0;
2045 flags = &localflags;
2046 }
2047 if (n) {
2048 flags->cf_flags |= iflags & PyCF_MASK;
2049 mod = PyAST_FromNode(n, flags, filename, arena);
2050 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 }
2052 else {
2053 err_input(&err);
2054 if (errcode)
2055 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002056 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002058 err_free(&err);
2059 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002060}
2061
Guido van Rossuma110aa61994-08-29 12:50:44 +00002062/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002063
Guido van Rossuma110aa61994-08-29 12:50:44 +00002064node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002065PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 perrdetail err;
2068 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2069 &_PyParser_Grammar,
2070 start, NULL, NULL, &err, flags);
2071 if (n == NULL)
2072 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002073 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002076}
2077
Guido van Rossuma110aa61994-08-29 12:50:44 +00002078/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002079
Guido van Rossuma110aa61994-08-29 12:50:44 +00002080node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002081PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 perrdetail err;
2084 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2085 start, &err, flags);
2086 if (n == NULL)
2087 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002088 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002090}
2091
2092node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002093PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 perrdetail err;
2097 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2098 &_PyParser_Grammar, start, &err, flags);
2099 if (n == NULL)
2100 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002101 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002103}
2104
2105node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002106PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002109}
2110
Guido van Rossum66ebd912003-04-17 16:02:26 +00002111/* May want to move a more generalized form of this to parsetok.c or
2112 even parser modules. */
2113
2114void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002115PyParser_ClearError(perrdetail *err)
2116{
2117 err_free(err);
2118}
2119
2120void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002121PyParser_SetError(perrdetail *err)
2122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002124}
2125
Victor Stinner7f2fee32011-04-05 00:39:01 +02002126static void
2127err_free(perrdetail *err)
2128{
2129 Py_CLEAR(err->filename);
2130}
2131
Guido van Rossuma110aa61994-08-29 12:50:44 +00002132/* Set the error appropriate to the given input error code (see errcode.h) */
2133
2134static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002135err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 PyObject *v, *w, *errtype, *errtext;
2138 PyObject *msg_obj = NULL;
2139 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 errtype = PyExc_SyntaxError;
2142 switch (err->error) {
2143 case E_ERROR:
2144 return;
2145 case E_SYNTAX:
2146 errtype = PyExc_IndentationError;
2147 if (err->expected == INDENT)
2148 msg = "expected an indented block";
2149 else if (err->token == INDENT)
2150 msg = "unexpected indent";
2151 else if (err->token == DEDENT)
2152 msg = "unexpected unindent";
2153 else {
2154 errtype = PyExc_SyntaxError;
2155 msg = "invalid syntax";
2156 }
2157 break;
2158 case E_TOKEN:
2159 msg = "invalid token";
2160 break;
2161 case E_EOFS:
2162 msg = "EOF while scanning triple-quoted string literal";
2163 break;
2164 case E_EOLS:
2165 msg = "EOL while scanning string literal";
2166 break;
2167 case E_INTR:
2168 if (!PyErr_Occurred())
2169 PyErr_SetNone(PyExc_KeyboardInterrupt);
2170 goto cleanup;
2171 case E_NOMEM:
2172 PyErr_NoMemory();
2173 goto cleanup;
2174 case E_EOF:
2175 msg = "unexpected EOF while parsing";
2176 break;
2177 case E_TABSPACE:
2178 errtype = PyExc_TabError;
2179 msg = "inconsistent use of tabs and spaces in indentation";
2180 break;
2181 case E_OVERFLOW:
2182 msg = "expression too long";
2183 break;
2184 case E_DEDENT:
2185 errtype = PyExc_IndentationError;
2186 msg = "unindent does not match any outer indentation level";
2187 break;
2188 case E_TOODEEP:
2189 errtype = PyExc_IndentationError;
2190 msg = "too many levels of indentation";
2191 break;
2192 case E_DECODE: {
2193 PyObject *type, *value, *tb;
2194 PyErr_Fetch(&type, &value, &tb);
2195 msg = "unknown decode error";
2196 if (value != NULL)
2197 msg_obj = PyObject_Str(value);
2198 Py_XDECREF(type);
2199 Py_XDECREF(value);
2200 Py_XDECREF(tb);
2201 break;
2202 }
2203 case E_LINECONT:
2204 msg = "unexpected character after line continuation character";
2205 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 case E_IDENTIFIER:
2208 msg = "invalid character in identifier";
2209 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002210 case E_BADSINGLE:
2211 msg = "multiple statements found while compiling a single statement";
2212 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 default:
2214 fprintf(stderr, "error=%d\n", err->error);
2215 msg = "unknown parsing error";
2216 break;
2217 }
2218 /* err->text may not be UTF-8 in case of decoding errors.
2219 Explicitly convert to an object. */
2220 if (!err->text) {
2221 errtext = Py_None;
2222 Py_INCREF(Py_None);
2223 } else {
2224 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2225 "replace");
2226 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002227 v = Py_BuildValue("(OiiN)", err->filename,
2228 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 if (v != NULL) {
2230 if (msg_obj)
2231 w = Py_BuildValue("(OO)", msg_obj, v);
2232 else
2233 w = Py_BuildValue("(sO)", msg, v);
2234 } else
2235 w = NULL;
2236 Py_XDECREF(v);
2237 PyErr_SetObject(errtype, w);
2238 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002239cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 Py_XDECREF(msg_obj);
2241 if (err->text != NULL) {
2242 PyObject_FREE(err->text);
2243 err->text = NULL;
2244 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002245}
2246
2247/* Print fatal error message and abort */
2248
2249void
Tim Peters7c321a82002-07-09 02:57:01 +00002250Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002251{
Victor Stinner024e37a2011-03-31 01:31:06 +02002252 const int fd = fileno(stderr);
2253 PyThreadState *tstate;
2254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 fprintf(stderr, "Fatal Python error: %s\n", msg);
2256 fflush(stderr); /* it helps in Windows debug build */
2257 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002258 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002260 else {
2261 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2262 if (tstate != NULL) {
2263 fputc('\n', stderr);
2264 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002265 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002266 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002267 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002268 }
2269
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002270#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 {
2272 size_t len = strlen(msg);
2273 WCHAR* buffer;
2274 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 /* Convert the message to wchar_t. This uses a simple one-to-one
2277 conversion, assuming that the this error message actually uses ASCII
2278 only. If this ceases to be true, we will have to convert. */
2279 buffer = alloca( (len+1) * (sizeof *buffer));
2280 for( i=0; i<=len; ++i)
2281 buffer[i] = msg[i];
2282 OutputDebugStringW(L"Fatal Python error: ");
2283 OutputDebugStringW(buffer);
2284 OutputDebugStringW(L"\n");
2285 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002286#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002288#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002289#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002291}
2292
2293/* Clean up and exit */
2294
Guido van Rossuma110aa61994-08-29 12:50:44 +00002295#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002296#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002297#endif
2298
Collin Winter670e6922007-03-21 02:57:17 +00002299static void (*pyexitfunc)(void) = NULL;
2300/* For the atexit module. */
2301void _Py_PyAtExit(void (*func)(void))
2302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002304}
2305
2306static void
2307call_py_exitfuncs(void)
2308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 if (pyexitfunc == NULL)
2310 return;
Collin Winter670e6922007-03-21 02:57:17 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 (*pyexitfunc)();
2313 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002314}
2315
Antoine Pitrou011bd622009-10-20 21:52:47 +00002316/* Wait until threading._shutdown completes, provided
2317 the threading module was imported in the first place.
2318 The shutdown routine will wait until all non-daemon
2319 "threading" threads have completed. */
2320static void
2321wait_for_thread_shutdown(void)
2322{
2323#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002324 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 PyObject *result;
2326 PyThreadState *tstate = PyThreadState_GET();
2327 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2328 "threading");
2329 if (threading == NULL) {
2330 /* threading not imported */
2331 PyErr_Clear();
2332 return;
2333 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002334 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (result == NULL) {
2336 PyErr_WriteUnraisable(threading);
2337 }
2338 else {
2339 Py_DECREF(result);
2340 }
2341 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002342#endif
2343}
2344
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002345#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002346static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002347static int nexitfuncs = 0;
2348
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002349int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 if (nexitfuncs >= NEXITFUNCS)
2352 return -1;
2353 exitfuncs[nexitfuncs++] = func;
2354 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002355}
2356
Guido van Rossumcc283f51997-08-05 02:22:03 +00002357static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002358call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 while (nexitfuncs > 0)
2361 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 fflush(stdout);
2364 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002365}
2366
2367void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002368Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002373}
2374
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002375static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002376initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002377{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002378#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002380#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002381#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002383#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002384#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002386#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002388}
2389
Guido van Rossum7433b121997-02-14 19:45:36 +00002390
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002391/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2392 *
2393 * All of the code in this function must only use async-signal-safe functions,
2394 * listed at `man 7 signal` or
2395 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2396 */
2397void
2398_Py_RestoreSignals(void)
2399{
2400#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002402#endif
2403#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002405#endif
2406#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002408#endif
2409}
2410
2411
Guido van Rossum7433b121997-02-14 19:45:36 +00002412/*
2413 * The file descriptor fd is considered ``interactive'' if either
2414 * a) isatty(fd) is TRUE, or
2415 * b) the -i flag was given, and the filename associated with
2416 * the descriptor is NULL or "<stdin>" or "???".
2417 */
2418int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002419Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 if (isatty((int)fileno(fp)))
2422 return 1;
2423 if (!Py_InteractiveFlag)
2424 return 0;
2425 return (filename == NULL) ||
2426 (strcmp(filename, "<stdin>") == 0) ||
2427 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002428}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002429
2430
Tim Petersd08e3822003-04-17 15:24:21 +00002431#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002432#if defined(WIN32) && defined(_MSC_VER)
2433
2434/* Stack checking for Microsoft C */
2435
2436#include <malloc.h>
2437#include <excpt.h>
2438
Fred Drakee8de31c2000-08-31 05:38:39 +00002439/*
2440 * Return non-zero when we run out of memory on the stack; zero otherwise.
2441 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002442int
Fred Drake399739f2000-08-31 05:52:44 +00002443PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 __try {
2446 /* alloca throws a stack overflow exception if there's
2447 not enough space left on the stack */
2448 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2449 return 0;
2450 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2451 EXCEPTION_EXECUTE_HANDLER :
2452 EXCEPTION_CONTINUE_SEARCH) {
2453 int errcode = _resetstkoflw();
2454 if (errcode == 0)
2455 {
2456 Py_FatalError("Could not reset the stack!");
2457 }
2458 }
2459 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002460}
2461
2462#endif /* WIN32 && _MSC_VER */
2463
2464/* Alternate implementations can be added here... */
2465
2466#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002467
2468
2469/* Wrappers around sigaction() or signal(). */
2470
2471PyOS_sighandler_t
2472PyOS_getsig(int sig)
2473{
2474#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 struct sigaction context;
2476 if (sigaction(sig, NULL, &context) == -1)
2477 return SIG_ERR;
2478 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002479#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002481/* Special signal handling for the secure CRT in Visual Studio 2005 */
2482#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 switch (sig) {
2484 /* Only these signals are valid */
2485 case SIGINT:
2486 case SIGILL:
2487 case SIGFPE:
2488 case SIGSEGV:
2489 case SIGTERM:
2490 case SIGBREAK:
2491 case SIGABRT:
2492 break;
2493 /* Don't call signal() with other values or it will assert */
2494 default:
2495 return SIG_ERR;
2496 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002497#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 handler = signal(sig, SIG_IGN);
2499 if (handler != SIG_ERR)
2500 signal(sig, handler);
2501 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002502#endif
2503}
2504
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002505/*
2506 * All of the code in this function must only use async-signal-safe functions,
2507 * listed at `man 7 signal` or
2508 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2509 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002510PyOS_sighandler_t
2511PyOS_setsig(int sig, PyOS_sighandler_t handler)
2512{
2513#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 /* Some code in Modules/signalmodule.c depends on sigaction() being
2515 * used here if HAVE_SIGACTION is defined. Fix that if this code
2516 * changes to invalidate that assumption.
2517 */
2518 struct sigaction context, ocontext;
2519 context.sa_handler = handler;
2520 sigemptyset(&context.sa_mask);
2521 context.sa_flags = 0;
2522 if (sigaction(sig, &context, &ocontext) == -1)
2523 return SIG_ERR;
2524 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002525#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 PyOS_sighandler_t oldhandler;
2527 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002528#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002530#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002532#endif
2533}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002534
2535/* Deprecated C API functions still provided for binary compatiblity */
2536
2537#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002538PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002539PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542}
2543
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002544#undef PyParser_SimpleParseString
2545PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002546PyParser_SimpleParseString(const char *str, int start)
2547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002549}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002550
2551#undef PyRun_AnyFile
2552PyAPI_FUNC(int)
2553PyRun_AnyFile(FILE *fp, const char *name)
2554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002556}
2557
2558#undef PyRun_AnyFileEx
2559PyAPI_FUNC(int)
2560PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002563}
2564
2565#undef PyRun_AnyFileFlags
2566PyAPI_FUNC(int)
2567PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002570}
2571
2572#undef PyRun_File
2573PyAPI_FUNC(PyObject *)
2574PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002577}
2578
2579#undef PyRun_FileEx
2580PyAPI_FUNC(PyObject *)
2581PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002584}
2585
2586#undef PyRun_FileFlags
2587PyAPI_FUNC(PyObject *)
2588PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002592}
2593
2594#undef PyRun_SimpleFile
2595PyAPI_FUNC(int)
2596PyRun_SimpleFile(FILE *f, const char *p)
2597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002599}
2600
2601#undef PyRun_SimpleFileEx
2602PyAPI_FUNC(int)
2603PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002606}
2607
2608
2609#undef PyRun_String
2610PyAPI_FUNC(PyObject *)
2611PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002614}
2615
2616#undef PyRun_SimpleString
2617PyAPI_FUNC(int)
2618PyRun_SimpleString(const char *s)
2619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002621}
2622
2623#undef Py_CompileString
2624PyAPI_FUNC(PyObject *)
2625Py_CompileString(const char *str, const char *p, int s)
2626{
Georg Brandl8334fd92010-12-04 10:26:46 +00002627 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2628}
2629
2630#undef Py_CompileStringFlags
2631PyAPI_FUNC(PyObject *)
2632Py_CompileStringFlags(const char *str, const char *p, int s,
2633 PyCompilerFlags *flags)
2634{
2635 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002636}
2637
2638#undef PyRun_InteractiveOne
2639PyAPI_FUNC(int)
2640PyRun_InteractiveOne(FILE *f, const char *p)
2641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002643}
2644
2645#undef PyRun_InteractiveLoop
2646PyAPI_FUNC(int)
2647PyRun_InteractiveLoop(FILE *f, const char *p)
2648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002650}
2651
2652#ifdef __cplusplus
2653}
2654#endif