blob: cd3cf5c53c22bb42422aae2b2652b38e48c60cbd [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
Brett Cannone0d88a12012-04-25 20:54:04 -0400232 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400233 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");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200319 if (_PyUnicode_Init() < 0)
320 Py_FatalError("Py_Initialize: can't initialize unicode");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 bimod = _PyBuiltin_Init();
323 if (bimod == NULL)
324 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000325 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 interp->builtins = PyModule_GetDict(bimod);
327 if (interp->builtins == NULL)
328 Py_FatalError("Py_Initialize: can't initialize builtins dict");
329 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400332 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 sysmod = _PySys_Init();
335 if (sysmod == NULL)
336 Py_FatalError("Py_Initialize: can't initialize sys");
337 interp->sysdict = PyModule_GetDict(sysmod);
338 if (interp->sysdict == NULL)
339 Py_FatalError("Py_Initialize: can't initialize sys dict");
340 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000341 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 PySys_SetPath(Py_GetPath());
343 PyDict_SetItemString(interp->sysdict, "modules",
344 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 /* Set up a preliminary stderr printer until we have enough
347 infrastructure for the io module in place. */
348 pstderr = PyFile_NewStdPrinter(fileno(stderr));
349 if (pstderr == NULL)
350 Py_FatalError("Py_Initialize: can't set preliminary stderr");
351 PySys_SetObject("stderr", pstderr);
352 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000353 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000358
Victor Stinner024e37a2011-03-31 01:31:06 +0200359 /* initialize the faulthandler module */
360 if (_PyFaulthandler_Init())
361 Py_FatalError("Py_Initialize: can't initialize faulthandler");
362
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000363 /* Initialize _warnings. */
364 _PyWarnings_Init();
365
Brett Cannonfd074152012-04-14 14:10:13 -0400366 import_init(interp, sysmod);
367
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000368 _PyTime_Init();
369
Victor Stinner793b5312011-04-27 00:24:21 +0200370 if (initfsencoding(interp) < 0)
371 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 if (install_sigs)
374 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 initmain(); /* Module __main__ */
377 if (initstdio() < 0)
378 Py_FatalError(
379 "Py_Initialize: can't initialize sys standard streams");
380
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000381 /* Initialize warnings. */
382 if (PySys_HasWarnOptions()) {
383 PyObject *warnings_module = PyImport_ImportModule("warnings");
384 if (warnings_module == NULL) {
385 fprintf(stderr, "'import warnings' failed; traceback:\n");
386 PyErr_Print();
387 }
388 Py_XDECREF(warnings_module);
389 }
390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (!Py_NoSiteFlag)
392 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000393}
394
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000395void
396Py_Initialize(void)
397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000399}
400
401
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000402#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000403extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000404#endif
405
Guido van Rossume8432ac2007-07-09 15:04:50 +0000406/* Flush stdout and stderr */
407
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100408static int
409file_is_closed(PyObject *fobj)
410{
411 int r;
412 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
413 if (tmp == NULL) {
414 PyErr_Clear();
415 return 0;
416 }
417 r = PyObject_IsTrue(tmp);
418 Py_DECREF(tmp);
419 if (r < 0)
420 PyErr_Clear();
421 return r > 0;
422}
423
Neal Norwitz2bad9702007-08-27 06:19:22 +0000424static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000425flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyObject *fout = PySys_GetObject("stdout");
428 PyObject *ferr = PySys_GetObject("stderr");
429 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200430 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000431
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100432 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200433 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000435 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 else
437 Py_DECREF(tmp);
438 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000439
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100440 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200441 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (tmp == NULL)
443 PyErr_Clear();
444 else
445 Py_DECREF(tmp);
446 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000447}
448
Guido van Rossum25ce5661997-08-02 03:10:38 +0000449/* Undo the effect of Py_Initialize().
450
451 Beware: if multiple interpreter and/or thread states exist, these
452 are not wiped out; only the current thread and interpreter state
453 are deleted. But since everything else is deleted, those other
454 interpreter and thread states should no longer be used.
455
456 (XXX We should do better, e.g. wipe out all interpreters and
457 threads.)
458
459 Locking: as above.
460
461*/
462
463void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000464Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyInterpreterState *interp;
467 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (!initialized)
470 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* The interpreter is still entirely intact at this point, and the
475 * exit funcs may be relying on that. In particular, if some thread
476 * or exit func is still waiting to do an import, the import machinery
477 * expects Py_IsInitialized() to return true. So don't say the
478 * interpreter is uninitialized until after the exit funcs have run.
479 * Note that Threading.py uses an exit func to do a join on all the
480 * threads created thru it, so this also protects pending imports in
481 * the threads created via Threading.
482 */
483 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* Get current thread state and interpreter pointer */
486 tstate = PyThreadState_GET();
487 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000488
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200489 /* Remaining threads (e.g. daemon threads) will automatically exit
490 after taking the GIL (in PyEval_RestoreThread()). */
491 _Py_Finalizing = tstate;
492 initialized = 0;
493
494 /* Flush stdout+stderr */
495 flush_std_files();
496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 /* Disable signal handling */
498 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* Clear type lookup cache */
501 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* Collect garbage. This may call finalizers; it's nice to call these
504 * before all modules are destroyed.
505 * XXX If a __del__ or weakref callback is triggered here, and tries to
506 * XXX import a module, bad things can happen, because Python no
507 * XXX longer believes it's initialized.
508 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
509 * XXX is easy to provoke that way. I've also seen, e.g.,
510 * XXX Exception exceptions.ImportError: 'No module named sha'
511 * XXX in <function callback at 0x008F5718> ignored
512 * XXX but I'm unclear on exactly how that one happens. In any case,
513 * XXX I haven't seen a real-life report of either of these.
514 */
515 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000516#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* With COUNT_ALLOCS, it helps to run GC multiple times:
518 each collection might release some types from the type
519 list, so they become garbage. */
520 while (PyGC_Collect() > 0)
521 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000522#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000523 /* We run this while most interpreter state is still alive, so that
524 debug information can be printed out */
525 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 /* Destroy all modules */
528 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 /* Flush stdout+stderr (again, in case more was printed) */
531 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100534 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 * XXX This is disabled because it caused too many problems. If
536 * XXX a __del__ or weakref callback triggers here, Python code has
537 * XXX a hard time running, because even the sys module has been
538 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
539 * XXX One symptom is a sequence of information-free messages
540 * XXX coming from threads (if a __del__ or callback is invoked,
541 * XXX other threads can execute too, and any exception they encounter
542 * XXX triggers a comedy of errors as subsystem after subsystem
543 * XXX fails to find what it *expects* to find in sys to help report
544 * XXX the exception and consequent unexpected failures). I've also
545 * XXX seen segfaults then, after adding print statements to the
546 * XXX Python code getting called.
547 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000548#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000550#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
553 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000554
Victor Stinner024e37a2011-03-31 01:31:06 +0200555 /* unload faulthandler module */
556 _PyFaulthandler_Fini();
557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000559#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000561#endif
562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000564
Tim Peters9cf25ce2003-04-17 15:21:01 +0000565#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 /* Display all objects still alive -- this can invoke arbitrary
567 * __repr__ overrides, so requires a mostly-intact interpreter.
568 * Alas, a lot of stuff may still be alive now that will be cleaned
569 * up later.
570 */
571 if (Py_GETENV("PYTHONDUMPREFS"))
572 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000573#endif /* Py_TRACE_REFS */
574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 /* Clear interpreter state */
576 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* Now we decref the exception classes. After this point nothing
579 can raise an exception. That's okay, because each Fini() method
580 below has been checked to make sure no exceptions are ever
581 raised.
582 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000587#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000589#endif /* WITH_THREAD */
590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 /* Delete current thread */
592 PyThreadState_Swap(NULL);
593 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 /* Sundry finalizers */
596 PyMethod_Fini();
597 PyFrame_Fini();
598 PyCFunction_Fini();
599 PyTuple_Fini();
600 PyList_Fini();
601 PySet_Fini();
602 PyBytes_Fini();
603 PyByteArray_Fini();
604 PyLong_Fini();
605 PyFloat_Fini();
606 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100607 PySlice_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 /* Cleanup Unicode implementation */
610 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000613 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 free((char*)Py_FileSystemDefaultEncoding);
615 Py_FileSystemDefaultEncoding = NULL;
616 }
Christian Heimesc8967002007-11-30 10:18:26 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 /* XXX Still allocated:
619 - various static ad-hoc pointers to interned strings
620 - int and float free list blocks
621 - whatever various modules and libraries allocate
622 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000625
Tim Peters269b2a62003-04-17 19:52:29 +0000626#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 /* Display addresses (& refcnts) of all objects still alive.
628 * An address can be used to find the repr of the object, printed
629 * above by _Py_PrintReferences.
630 */
631 if (Py_GETENV("PYTHONDUMPREFS"))
632 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000633#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000634#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (Py_GETENV("PYTHONMALLOCSTATS"))
636 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000637#endif
638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000640}
641
642/* Create and initialize a new interpreter and thread, and return the
643 new thread. This requires that Py_Initialize() has been called
644 first.
645
646 Unsuccessful initialization yields a NULL pointer. Note that *no*
647 exception information is available even in this case -- the
648 exception information is held in the thread, and there is no
649 thread.
650
651 Locking: as above.
652
653*/
654
655PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000656Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyInterpreterState *interp;
659 PyThreadState *tstate, *save_tstate;
660 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 if (!initialized)
663 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 interp = PyInterpreterState_New();
666 if (interp == NULL)
667 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 tstate = PyThreadState_New(interp);
670 if (tstate == NULL) {
671 PyInterpreterState_Delete(interp);
672 return NULL;
673 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000680
Victor Stinner49d3f252010-10-17 01:24:53 +0000681 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (bimod != NULL) {
683 interp->builtins = PyModule_GetDict(bimod);
684 if (interp->builtins == NULL)
685 goto handle_error;
686 Py_INCREF(interp->builtins);
687 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400690 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000691
Victor Stinner49d3f252010-10-17 01:24:53 +0000692 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (bimod != NULL && sysmod != NULL) {
694 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 interp->sysdict = PyModule_GetDict(sysmod);
697 if (interp->sysdict == NULL)
698 goto handle_error;
699 Py_INCREF(interp->sysdict);
700 PySys_SetPath(Py_GetPath());
701 PyDict_SetItemString(interp->sysdict, "modules",
702 interp->modules);
703 /* Set up a preliminary stderr printer until we have enough
704 infrastructure for the io module in place. */
705 pstderr = PyFile_NewStdPrinter(fileno(stderr));
706 if (pstderr == NULL)
707 Py_FatalError("Py_Initialize: can't set preliminary stderr");
708 PySys_SetObject("stderr", pstderr);
709 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000710 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200713
Brett Cannonfd074152012-04-14 14:10:13 -0400714 import_init(interp, sysmod);
715
Victor Stinner793b5312011-04-27 00:24:21 +0200716 if (initfsencoding(interp) < 0)
717 goto handle_error;
718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 if (initstdio() < 0)
720 Py_FatalError(
721 "Py_Initialize: can't initialize sys standard streams");
722 initmain();
723 if (!Py_NoSiteFlag)
724 initsite();
725 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 if (!PyErr_Occurred())
728 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000729
Thomas Wouters89f507f2006-12-13 04:49:30 +0000730handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000732
Victor Stinnerc40a3502011-04-27 00:20:27 +0200733 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyThreadState_Clear(tstate);
735 PyThreadState_Swap(save_tstate);
736 PyThreadState_Delete(tstate);
737 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000740}
741
742/* Delete an interpreter and its last thread. This requires that the
743 given thread state is current, that the thread has no remaining
744 frames, and that it is its interpreter's only remaining thread.
745 It is a fatal error to violate these constraints.
746
747 (Py_Finalize() doesn't have these constraints -- it zaps
748 everything, regardless.)
749
750 Locking: as above.
751
752*/
753
754void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000755Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 if (tstate != PyThreadState_GET())
760 Py_FatalError("Py_EndInterpreter: thread is not current");
761 if (tstate->frame != NULL)
762 Py_FatalError("Py_EndInterpreter: thread still has a frame");
763 if (tstate != interp->tstate_head || tstate->next != NULL)
764 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyImport_Cleanup();
767 PyInterpreterState_Clear(interp);
768 PyThreadState_Swap(NULL);
769 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000770}
771
Martin v. Löwis790465f2008-04-05 20:41:37 +0000772static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000773
774void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000775Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 if (pn && *pn)
778 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000779}
780
Martin v. Löwis790465f2008-04-05 20:41:37 +0000781wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000782Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000785}
786
Martin v. Löwis790465f2008-04-05 20:41:37 +0000787static wchar_t *default_home = NULL;
788static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000789
790void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000791Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000794}
795
Martin v. Löwis790465f2008-04-05 20:41:37 +0000796wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000797Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 wchar_t *home = default_home;
800 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
801 char* chome = Py_GETENV("PYTHONHOME");
802 if (chome) {
803 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
804 if (r != (size_t)-1 && r <= PATH_MAX)
805 home = env_home;
806 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 }
809 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000810}
811
Guido van Rossum6135a871995-01-09 17:53:26 +0000812/* Create __main__ module */
813
814static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000815initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyObject *m, *d;
818 m = PyImport_AddModule("__main__");
819 if (m == NULL)
820 Py_FatalError("can't create __main__ module");
821 d = PyModule_GetDict(m);
822 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
823 PyObject *bimod = PyImport_ImportModule("builtins");
824 if (bimod == NULL ||
825 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
826 Py_FatalError("can't add __builtins__ to __main__");
827 Py_DECREF(bimod);
828 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000829}
830
Victor Stinner793b5312011-04-27 00:24:21 +0200831static int
832initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000833{
834 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000835
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200836 if (Py_FileSystemDefaultEncoding == NULL)
837 {
838 Py_FileSystemDefaultEncoding = get_locale_encoding();
839 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000840 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000841
Victor Stinnere4743092010-10-19 00:05:51 +0000842 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200843 interp->fscodec_initialized = 1;
844 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000845 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000846
847 /* the encoding is mbcs, utf-8 or ascii */
848 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
849 if (!codec) {
850 /* Such error can only occurs in critical situations: no more
851 * memory, import a module of the standard library failed,
852 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200853 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000854 }
Victor Stinner793b5312011-04-27 00:24:21 +0200855 Py_DECREF(codec);
856 interp->fscodec_initialized = 1;
857 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000858}
859
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000860/* Import the site module (not into __main__ though) */
861
862static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000863initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 PyObject *m;
866 m = PyImport_ImportModule("site");
867 if (m == NULL) {
868 PyErr_Print();
869 Py_Finalize();
870 exit(1);
871 }
872 else {
873 Py_DECREF(m);
874 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000875}
876
Antoine Pitrou05608432009-01-09 18:53:14 +0000877static PyObject*
878create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 int fd, int write_mode, char* name,
880 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
883 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000884 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 PyObject *line_buffering;
886 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200887 _Py_IDENTIFIER(open);
888 _Py_IDENTIFIER(isatty);
889 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200890 _Py_IDENTIFIER(name);
891 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 /* stdin is always opened in buffered mode, first because it shouldn't
894 make a difference in common use cases, second because TextIOWrapper
895 depends on the presence of a read1() method which only exists on
896 buffered streams.
897 */
898 if (Py_UnbufferedStdioFlag && write_mode)
899 buffering = 0;
900 else
901 buffering = -1;
902 if (write_mode)
903 mode = "wb";
904 else
905 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200906 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
907 fd, mode, buffering,
908 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 if (buf == NULL)
910 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200913 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200914 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 if (raw == NULL)
916 goto error;
917 }
918 else {
919 raw = buf;
920 Py_INCREF(raw);
921 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200924 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200926 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 if (res == NULL)
928 goto error;
929 isatty = PyObject_IsTrue(res);
930 Py_DECREF(res);
931 if (isatty == -1)
932 goto error;
933 if (isatty || Py_UnbufferedStdioFlag)
934 line_buffering = Py_True;
935 else
936 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 Py_CLEAR(raw);
939 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000940
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000941 newline = "\n";
942#ifdef MS_WINDOWS
943 if (!write_mode) {
944 /* translate \r\n to \n for sys.stdin on Windows */
945 newline = NULL;
946 }
947#endif
948
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200949 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
950 buf, encoding, errors,
951 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 Py_CLEAR(buf);
953 if (stream == NULL)
954 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (write_mode)
957 mode = "w";
958 else
959 mode = "r";
960 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200961 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 goto error;
963 Py_CLEAR(text);
964 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000965
966error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 Py_XDECREF(buf);
968 Py_XDECREF(stream);
969 Py_XDECREF(text);
970 Py_XDECREF(raw);
971 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000972}
973
Antoine Pitrou11942a52011-11-28 19:08:36 +0100974static int
975is_valid_fd(int fd)
976{
977 int dummy_fd;
978 if (fd < 0 || !_PyVerify_fd(fd))
979 return 0;
980 dummy_fd = dup(fd);
981 if (dummy_fd < 0)
982 return 0;
983 close(dummy_fd);
984 return 1;
985}
986
Georg Brandl1a3284e2007-12-02 09:40:06 +0000987/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000988static int
989initstdio(void)
990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyObject *iomod = NULL, *wrapper;
992 PyObject *bimod = NULL;
993 PyObject *m;
994 PyObject *std = NULL;
995 int status = 0, fd;
996 PyObject * encoding_attr;
997 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* Hack to avoid a nasty recursion issue when Python is invoked
1000 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1001 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1002 goto error;
1003 }
1004 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1007 goto error;
1008 }
1009 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 if (!(bimod = PyImport_ImportModule("builtins"))) {
1012 goto error;
1013 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (!(iomod = PyImport_ImportModule("io"))) {
1016 goto error;
1017 }
1018 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1019 goto error;
1020 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 /* Set builtins.open */
1023 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001024 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 goto error;
1026 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001027 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 encoding = Py_GETENV("PYTHONIOENCODING");
1030 errors = NULL;
1031 if (encoding) {
1032 encoding = strdup(encoding);
1033 errors = strchr(encoding, ':');
1034 if (errors) {
1035 *errors = '\0';
1036 errors++;
1037 }
1038 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 /* Set sys.stdin */
1041 fd = fileno(stdin);
1042 /* Under some conditions stdin, stdout and stderr may not be connected
1043 * and fileno() may point to an invalid file descriptor. For example
1044 * GUI apps don't have valid standard streams by default.
1045 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001046 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 std = Py_None;
1048 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 }
1050 else {
1051 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1052 if (std == NULL)
1053 goto error;
1054 } /* if (fd < 0) */
1055 PySys_SetObject("__stdin__", std);
1056 PySys_SetObject("stdin", std);
1057 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 /* Set sys.stdout */
1060 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001061 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 std = Py_None;
1063 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 }
1065 else {
1066 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1067 if (std == NULL)
1068 goto error;
1069 } /* if (fd < 0) */
1070 PySys_SetObject("__stdout__", std);
1071 PySys_SetObject("stdout", std);
1072 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001073
Guido van Rossum98297ee2007-11-06 21:34:58 +00001074#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 /* Set sys.stderr, replaces the preliminary stderr */
1076 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001077 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 std = Py_None;
1079 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 }
1081 else {
1082 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1083 if (std == NULL)
1084 goto error;
1085 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 /* Same as hack above, pre-import stderr's codec to avoid recursion
1088 when import.c tries to write to stderr in verbose mode. */
1089 encoding_attr = PyObject_GetAttrString(std, "encoding");
1090 if (encoding_attr != NULL) {
1091 const char * encoding;
1092 encoding = _PyUnicode_AsString(encoding_attr);
1093 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001094 PyObject *codec_info = _PyCodec_Lookup(encoding);
1095 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001097 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 }
1099 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PySys_SetObject("__stderr__", std);
1102 PySys_SetObject("stderr", std);
1103 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001104#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001107 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 status = -1;
1109 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (encoding)
1112 free(encoding);
1113 Py_XDECREF(bimod);
1114 Py_XDECREF(iomod);
1115 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001116}
1117
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001118/* Parse input from a file and execute it */
1119
1120int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001121PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (filename == NULL)
1125 filename = "???";
1126 if (Py_FdIsInteractive(fp, filename)) {
1127 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1128 if (closeit)
1129 fclose(fp);
1130 return err;
1131 }
1132 else
1133 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001134}
1135
1136int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001137PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 PyObject *v;
1140 int ret;
1141 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (flags == NULL) {
1144 flags = &local_flags;
1145 local_flags.cf_flags = 0;
1146 }
1147 v = PySys_GetObject("ps1");
1148 if (v == NULL) {
1149 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1150 Py_XDECREF(v);
1151 }
1152 v = PySys_GetObject("ps2");
1153 if (v == NULL) {
1154 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1155 Py_XDECREF(v);
1156 }
1157 for (;;) {
1158 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1159 PRINT_TOTAL_REFS();
1160 if (ret == E_EOF)
1161 return 0;
1162 /*
1163 if (ret == E_NOMEM)
1164 return -1;
1165 */
1166 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001167}
1168
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001169/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001170static int PARSER_FLAGS(PyCompilerFlags *flags)
1171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 int parser_flags = 0;
1173 if (!flags)
1174 return 0;
1175 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1176 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1177 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1178 parser_flags |= PyPARSE_IGNORE_COOKIE;
1179 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1180 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1181 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001182}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001183
Thomas Wouters89f507f2006-12-13 04:49:30 +00001184#if 0
1185/* Keep an example of flags with future keyword support. */
1186#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1188 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1189 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1190 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001191#endif
1192
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001193int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001194PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 PyObject *m, *d, *v, *w, *oenc = NULL;
1197 mod_ty mod;
1198 PyArena *arena;
1199 char *ps1 = "", *ps2 = "", *enc = NULL;
1200 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001201 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (fp == stdin) {
1204 /* Fetch encoding from sys.stdin */
1205 v = PySys_GetObject("stdin");
1206 if (v == NULL || v == Py_None)
1207 return -1;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001208 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 if (!oenc)
1210 return -1;
1211 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001212 if (enc == NULL)
1213 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 }
1215 v = PySys_GetObject("ps1");
1216 if (v != NULL) {
1217 v = PyObject_Str(v);
1218 if (v == NULL)
1219 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001220 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001222 if (ps1 == NULL) {
1223 PyErr_Clear();
1224 ps1 = "";
1225 }
1226 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 }
1228 w = PySys_GetObject("ps2");
1229 if (w != NULL) {
1230 w = PyObject_Str(w);
1231 if (w == NULL)
1232 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001233 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001235 if (ps2 == NULL) {
1236 PyErr_Clear();
1237 ps2 = "";
1238 }
1239 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 }
1241 arena = PyArena_New();
1242 if (arena == NULL) {
1243 Py_XDECREF(v);
1244 Py_XDECREF(w);
1245 Py_XDECREF(oenc);
1246 return -1;
1247 }
1248 mod = PyParser_ASTFromFile(fp, filename, enc,
1249 Py_single_input, ps1, ps2,
1250 flags, &errcode, arena);
1251 Py_XDECREF(v);
1252 Py_XDECREF(w);
1253 Py_XDECREF(oenc);
1254 if (mod == NULL) {
1255 PyArena_Free(arena);
1256 if (errcode == E_EOF) {
1257 PyErr_Clear();
1258 return E_EOF;
1259 }
1260 PyErr_Print();
1261 return -1;
1262 }
1263 m = PyImport_AddModule("__main__");
1264 if (m == NULL) {
1265 PyArena_Free(arena);
1266 return -1;
1267 }
1268 d = PyModule_GetDict(m);
1269 v = run_mod(mod, filename, d, d, flags, arena);
1270 PyArena_Free(arena);
1271 flush_io();
1272 if (v == NULL) {
1273 PyErr_Print();
1274 return -1;
1275 }
1276 Py_DECREF(v);
1277 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001278}
1279
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001280/* Check whether a file maybe a pyc file: Look at the extension,
1281 the file type, and, if we may close it, at the first few bytes. */
1282
1283static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001284maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1287 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 /* Only look into the file if we are allowed to close it, since
1290 it then should also be seekable. */
1291 if (closeit) {
1292 /* Read only two bytes of the magic. If the file was opened in
1293 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1294 be read as they are on disk. */
1295 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1296 unsigned char buf[2];
1297 /* Mess: In case of -x, the stream is NOT at its start now,
1298 and ungetc() was used to push back the first newline,
1299 which makes the current stream position formally undefined,
1300 and a x-platform nightmare.
1301 Unfortunately, we have no direct way to know whether -x
1302 was specified. So we use a terrible hack: if the current
1303 stream position is not 0, we assume -x was specified, and
1304 give up. Bug 132850 on SourceForge spells out the
1305 hopelessness of trying anything else (fseek and ftell
1306 don't work predictably x-platform for text-mode files).
1307 */
1308 int ispyc = 0;
1309 if (ftell(fp) == 0) {
1310 if (fread(buf, 1, 2, fp) == 2 &&
1311 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1312 ispyc = 1;
1313 rewind(fp);
1314 }
1315 return ispyc;
1316 }
1317 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001318}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001319
Guido van Rossum0df002c2000-08-27 19:21:52 +00001320int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001321PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 PyObject *m, *d, *v;
1325 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001326 int set_file_name = 0, ret;
1327 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 m = PyImport_AddModule("__main__");
1330 if (m == NULL)
1331 return -1;
1332 d = PyModule_GetDict(m);
1333 if (PyDict_GetItemString(d, "__file__") == NULL) {
1334 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001335 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (f == NULL)
1337 return -1;
1338 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1339 Py_DECREF(f);
1340 return -1;
1341 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001342 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1343 Py_DECREF(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 return -1;
Barry Warsaw916048d2011-09-20 14:45:44 -04001345 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 set_file_name = 1;
1347 Py_DECREF(f);
1348 }
1349 len = strlen(filename);
1350 ext = filename + len - (len > 4 ? 4 : 0);
1351 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1352 /* Try to run a pyc file. First, re-open in binary */
1353 if (closeit)
1354 fclose(fp);
1355 if ((fp = fopen(filename, "rb")) == NULL) {
1356 fprintf(stderr, "python: Can't reopen .pyc file\n");
1357 ret = -1;
1358 goto done;
1359 }
1360 /* Turn on optimization if a .pyo file is given */
1361 if (strcmp(ext, ".pyo") == 0)
1362 Py_OptimizeFlag = 1;
1363 v = run_pyc_file(fp, filename, d, d, flags);
1364 } else {
1365 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1366 closeit, flags);
1367 }
1368 flush_io();
1369 if (v == NULL) {
1370 PyErr_Print();
1371 ret = -1;
1372 goto done;
1373 }
1374 Py_DECREF(v);
1375 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001376 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1378 PyErr_Clear();
1379 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001380}
1381
1382int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001383PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 PyObject *m, *d, *v;
1386 m = PyImport_AddModule("__main__");
1387 if (m == NULL)
1388 return -1;
1389 d = PyModule_GetDict(m);
1390 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1391 if (v == NULL) {
1392 PyErr_Print();
1393 return -1;
1394 }
1395 Py_DECREF(v);
1396 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001397}
1398
Barry Warsaw035574d1997-08-29 22:07:17 +00001399static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001400parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 long hold;
1404 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001405 _Py_IDENTIFIER(msg);
1406 _Py_IDENTIFIER(filename);
1407 _Py_IDENTIFIER(lineno);
1408 _Py_IDENTIFIER(offset);
1409 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001410
Benjamin Peterson80d50422012-04-03 00:30:38 -04001411 *message = NULL;
1412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001414 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001415 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001417
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001418 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001419 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001421 if (v == Py_None) {
1422 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001424 }
1425 else {
1426 *filename = _PyUnicode_AsString(v);
1427 Py_DECREF(v);
1428 if (!*filename)
1429 goto finally;
1430 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001431
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001432 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001433 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 goto finally;
1435 hold = PyLong_AsLong(v);
1436 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (hold < 0 && PyErr_Occurred())
1438 goto finally;
1439 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001440
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001441 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001442 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 goto finally;
1444 if (v == Py_None) {
1445 *offset = -1;
1446 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 } else {
1448 hold = PyLong_AsLong(v);
1449 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 if (hold < 0 && PyErr_Occurred())
1451 goto finally;
1452 *offset = (int)hold;
1453 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001454
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001455 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001456 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001458 if (v == Py_None) {
1459 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001461 }
1462 else {
1463 *text = _PyUnicode_AsString(v);
1464 Py_DECREF(v);
1465 if (!*text)
1466 goto finally;
1467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001469
1470finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001471 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001473}
1474
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001475void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001476PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001479}
1480
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001481static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001482print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 char *nl;
1485 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001486 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1487 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 for (;;) {
1489 nl = strchr(text, '\n');
1490 if (nl == NULL || nl-text >= offset)
1491 break;
1492 offset -= (int)(nl+1-text);
1493 text = nl+1;
1494 }
1495 while (*text == ' ' || *text == '\t') {
1496 text++;
1497 offset--;
1498 }
1499 }
1500 PyFile_WriteString(" ", f);
1501 PyFile_WriteString(text, f);
1502 if (*text == '\0' || text[strlen(text)-1] != '\n')
1503 PyFile_WriteString("\n", f);
1504 if (offset == -1)
1505 return;
1506 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001507 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001510}
1511
Guido van Rossum66e8e862001-03-23 17:54:43 +00001512static void
1513handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 PyObject *exception, *value, *tb;
1516 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 if (Py_InspectFlag)
1519 /* Don't exit if -i flag was given. This flag is set to 0
1520 * when entering interactive mode for inspecting. */
1521 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 PyErr_Fetch(&exception, &value, &tb);
1524 fflush(stdout);
1525 if (value == NULL || value == Py_None)
1526 goto done;
1527 if (PyExceptionInstance_Check(value)) {
1528 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001529 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001530 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 if (code) {
1532 Py_DECREF(value);
1533 value = code;
1534 if (value == Py_None)
1535 goto done;
1536 }
1537 /* If we failed to dig out the 'code' attribute,
1538 just let the else clause below print the error. */
1539 }
1540 if (PyLong_Check(value))
1541 exitcode = (int)PyLong_AsLong(value);
1542 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001543 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001544 if (sys_stderr != NULL && sys_stderr != Py_None) {
1545 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1546 } else {
1547 PyObject_Print(value, stderr, Py_PRINT_RAW);
1548 fflush(stderr);
1549 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 PySys_WriteStderr("\n");
1551 exitcode = 1;
1552 }
Tim Peterscf615b52003-04-19 18:47:02 +00001553 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 /* Restore and clear the exception info, in order to properly decref
1555 * the exception, value, and traceback. If we just exit instead,
1556 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1557 * some finalizers from running.
1558 */
1559 PyErr_Restore(exception, value, tb);
1560 PyErr_Clear();
1561 Py_Exit(exitcode);
1562 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001563}
1564
1565void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001566PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1571 handle_system_exit();
1572 }
1573 PyErr_Fetch(&exception, &v, &tb);
1574 if (exception == NULL)
1575 return;
1576 PyErr_NormalizeException(&exception, &v, &tb);
1577 if (tb == NULL) {
1578 tb = Py_None;
1579 Py_INCREF(tb);
1580 }
1581 PyException_SetTraceback(v, tb);
1582 if (exception == NULL)
1583 return;
1584 /* Now we know v != NULL too */
1585 if (set_sys_last_vars) {
1586 PySys_SetObject("last_type", exception);
1587 PySys_SetObject("last_value", v);
1588 PySys_SetObject("last_traceback", tb);
1589 }
1590 hook = PySys_GetObject("excepthook");
1591 if (hook) {
1592 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1593 PyObject *result = PyEval_CallObject(hook, args);
1594 if (result == NULL) {
1595 PyObject *exception2, *v2, *tb2;
1596 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1597 handle_system_exit();
1598 }
1599 PyErr_Fetch(&exception2, &v2, &tb2);
1600 PyErr_NormalizeException(&exception2, &v2, &tb2);
1601 /* It should not be possible for exception2 or v2
1602 to be NULL. However PyErr_Display() can't
1603 tolerate NULLs, so just be safe. */
1604 if (exception2 == NULL) {
1605 exception2 = Py_None;
1606 Py_INCREF(exception2);
1607 }
1608 if (v2 == NULL) {
1609 v2 = Py_None;
1610 Py_INCREF(v2);
1611 }
1612 fflush(stdout);
1613 PySys_WriteStderr("Error in sys.excepthook:\n");
1614 PyErr_Display(exception2, v2, tb2);
1615 PySys_WriteStderr("\nOriginal exception was:\n");
1616 PyErr_Display(exception, v, tb);
1617 Py_DECREF(exception2);
1618 Py_DECREF(v2);
1619 Py_XDECREF(tb2);
1620 }
1621 Py_XDECREF(result);
1622 Py_XDECREF(args);
1623 } else {
1624 PySys_WriteStderr("sys.excepthook is missing\n");
1625 PyErr_Display(exception, v, tb);
1626 }
1627 Py_XDECREF(exception);
1628 Py_XDECREF(v);
1629 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001630}
1631
Benjamin Petersone6528212008-07-15 15:32:09 +00001632static void
1633print_exception(PyObject *f, PyObject *value)
1634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 int err = 0;
1636 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001637 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (!PyExceptionInstance_Check(value)) {
1640 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1641 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1642 PyFile_WriteString(" found\n", f);
1643 return;
1644 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 Py_INCREF(value);
1647 fflush(stdout);
1648 type = (PyObject *) Py_TYPE(value);
1649 tb = PyException_GetTraceback(value);
1650 if (tb && tb != Py_None)
1651 err = PyTraceBack_Print(tb, f);
1652 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001653 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 {
1655 PyObject *message;
1656 const char *filename, *text;
1657 int lineno, offset;
1658 if (!parse_syntax_error(value, &message, &filename,
1659 &lineno, &offset, &text))
1660 PyErr_Clear();
1661 else {
1662 char buf[10];
1663 PyFile_WriteString(" File \"", f);
1664 if (filename == NULL)
1665 PyFile_WriteString("<string>", f);
1666 else
1667 PyFile_WriteString(filename, f);
1668 PyFile_WriteString("\", line ", f);
1669 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1670 PyFile_WriteString(buf, f);
1671 PyFile_WriteString("\n", f);
1672 if (text != NULL)
1673 print_error_text(f, offset, text);
1674 Py_DECREF(value);
1675 value = message;
1676 /* Can't be bothered to check all those
1677 PyFile_WriteString() calls */
1678 if (PyErr_Occurred())
1679 err = -1;
1680 }
1681 }
1682 if (err) {
1683 /* Don't do anything else */
1684 }
1685 else {
1686 PyObject* moduleName;
1687 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001688 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 assert(PyExceptionClass_Check(type));
1690 className = PyExceptionClass_Name(type);
1691 if (className != NULL) {
1692 char *dot = strrchr(className, '.');
1693 if (dot != NULL)
1694 className = dot+1;
1695 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001696
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001697 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1699 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001700 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 err = PyFile_WriteString("<unknown>", f);
1702 }
1703 else {
1704 char* modstr = _PyUnicode_AsString(moduleName);
1705 if (modstr && strcmp(modstr, "builtins"))
1706 {
1707 err = PyFile_WriteString(modstr, f);
1708 err += PyFile_WriteString(".", f);
1709 }
1710 Py_DECREF(moduleName);
1711 }
1712 if (err == 0) {
1713 if (className == NULL)
1714 err = PyFile_WriteString("<unknown>", f);
1715 else
1716 err = PyFile_WriteString(className, f);
1717 }
1718 }
1719 if (err == 0 && (value != Py_None)) {
1720 PyObject *s = PyObject_Str(value);
1721 /* only print colon if the str() of the
1722 object is not the empty string
1723 */
1724 if (s == NULL)
1725 err = -1;
1726 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001727 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 err = PyFile_WriteString(": ", f);
1729 if (err == 0)
1730 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1731 Py_XDECREF(s);
1732 }
1733 /* try to write a newline in any case */
1734 err += PyFile_WriteString("\n", f);
1735 Py_XDECREF(tb);
1736 Py_DECREF(value);
1737 /* If an error happened here, don't show it.
1738 XXX This is wrong, but too many callers rely on this behavior. */
1739 if (err != 0)
1740 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001741}
1742
1743static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 "\nThe above exception was the direct cause "
1745 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001746
1747static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 "\nDuring handling of the above exception, "
1749 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001750
1751static void
1752print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 int err = 0, res;
1755 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 if (seen != NULL) {
1758 /* Exception chaining */
1759 if (PySet_Add(seen, value) == -1)
1760 PyErr_Clear();
1761 else if (PyExceptionInstance_Check(value)) {
1762 cause = PyException_GetCause(value);
1763 context = PyException_GetContext(value);
Nick Coghlanab7bf212012-02-26 17:49:52 +10001764 if (cause && cause == Py_None) {
1765 /* print neither cause nor context */
1766 ;
1767 }
1768 else if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 res = PySet_Contains(seen, cause);
1770 if (res == -1)
1771 PyErr_Clear();
1772 if (res == 0) {
1773 print_exception_recursive(
1774 f, cause, seen);
1775 err |= PyFile_WriteString(
1776 cause_message, f);
1777 }
1778 }
1779 else if (context) {
1780 res = PySet_Contains(seen, context);
1781 if (res == -1)
1782 PyErr_Clear();
1783 if (res == 0) {
1784 print_exception_recursive(
1785 f, context, seen);
1786 err |= PyFile_WriteString(
1787 context_message, f);
1788 }
1789 }
1790 Py_XDECREF(context);
1791 Py_XDECREF(cause);
1792 }
1793 }
1794 print_exception(f, value);
1795 if (err != 0)
1796 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001797}
1798
Thomas Wouters477c8d52006-05-27 19:21:47 +00001799void
1800PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 PyObject *seen;
1803 PyObject *f = PySys_GetObject("stderr");
1804 if (f == Py_None) {
1805 /* pass */
1806 }
1807 else if (f == NULL) {
1808 _PyObject_Dump(value);
1809 fprintf(stderr, "lost sys.stderr\n");
1810 }
1811 else {
1812 /* We choose to ignore seen being possibly NULL, and report
1813 at least the main exception (it could be a MemoryError).
1814 */
1815 seen = PySet_New(NULL);
1816 if (seen == NULL)
1817 PyErr_Clear();
1818 print_exception_recursive(f, value, seen);
1819 Py_XDECREF(seen);
1820 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001821}
1822
Guido van Rossum82598051997-03-05 00:20:32 +00001823PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001824PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 PyObject *ret = NULL;
1828 mod_ty mod;
1829 PyArena *arena = PyArena_New();
1830 if (arena == NULL)
1831 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1834 if (mod != NULL)
1835 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1836 PyArena_Free(arena);
1837 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001838}
1839
1840PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001841PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 PyObject *ret;
1845 mod_ty mod;
1846 PyArena *arena = PyArena_New();
1847 if (arena == NULL)
1848 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1851 flags, NULL, arena);
1852 if (closeit)
1853 fclose(fp);
1854 if (mod == NULL) {
1855 PyArena_Free(arena);
1856 return NULL;
1857 }
1858 ret = run_mod(mod, filename, globals, locals, flags, arena);
1859 PyArena_Free(arena);
1860 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001861}
1862
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001863static void
1864flush_io(void)
1865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 PyObject *f, *r;
1867 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001868 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 /* Save the current exception */
1871 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 f = PySys_GetObject("stderr");
1874 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001875 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 if (r)
1877 Py_DECREF(r);
1878 else
1879 PyErr_Clear();
1880 }
1881 f = PySys_GetObject("stdout");
1882 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001883 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 if (r)
1885 Py_DECREF(r);
1886 else
1887 PyErr_Clear();
1888 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001891}
1892
Guido van Rossum82598051997-03-05 00:20:32 +00001893static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 PyCodeObject *co;
1898 PyObject *v;
1899 co = PyAST_Compile(mod, filename, flags, arena);
1900 if (co == NULL)
1901 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001902 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 Py_DECREF(co);
1904 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001905}
1906
Guido van Rossum82598051997-03-05 00:20:32 +00001907static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001908run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 PyCodeObject *co;
1912 PyObject *v;
1913 long magic;
1914 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 magic = PyMarshal_ReadLongFromFile(fp);
1917 if (magic != PyImport_GetMagicNumber()) {
1918 PyErr_SetString(PyExc_RuntimeError,
1919 "Bad magic number in .pyc file");
1920 return NULL;
1921 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001922 /* Skip mtime and size */
1923 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 (void) PyMarshal_ReadLongFromFile(fp);
1925 v = PyMarshal_ReadLastObjectFromFile(fp);
1926 fclose(fp);
1927 if (v == NULL || !PyCode_Check(v)) {
1928 Py_XDECREF(v);
1929 PyErr_SetString(PyExc_RuntimeError,
1930 "Bad code object in .pyc file");
1931 return NULL;
1932 }
1933 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001934 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 if (v && flags)
1936 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1937 Py_DECREF(co);
1938 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001939}
1940
Guido van Rossum82598051997-03-05 00:20:32 +00001941PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001942Py_CompileStringExFlags(const char *str, const char *filename, int start,
1943 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 PyCodeObject *co;
1946 mod_ty mod;
1947 PyArena *arena = PyArena_New();
1948 if (arena == NULL)
1949 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1952 if (mod == NULL) {
1953 PyArena_Free(arena);
1954 return NULL;
1955 }
1956 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1957 PyObject *result = PyAST_mod2obj(mod);
1958 PyArena_Free(arena);
1959 return result;
1960 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001961 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 PyArena_Free(arena);
1963 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001964}
1965
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001966/* For use in Py_LIMITED_API */
1967#undef Py_CompileString
1968PyObject *
1969PyCompileString(const char *str, const char *filename, int start)
1970{
1971 return Py_CompileStringFlags(str, filename, start, NULL);
1972}
1973
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001974struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001975Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 struct symtable *st;
1978 mod_ty mod;
1979 PyCompilerFlags flags;
1980 PyArena *arena = PyArena_New();
1981 if (arena == NULL)
1982 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 flags.cf_flags = 0;
1985 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1986 if (mod == NULL) {
1987 PyArena_Free(arena);
1988 return NULL;
1989 }
1990 st = PySymtable_Build(mod, filename, 0);
1991 PyArena_Free(arena);
1992 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001993}
1994
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001995/* Preferred access to parser is through AST. */
1996mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001997PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 mod_ty mod;
2001 PyCompilerFlags localflags;
2002 perrdetail err;
2003 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
2006 &_PyParser_Grammar, start, &err,
2007 &iflags);
2008 if (flags == NULL) {
2009 localflags.cf_flags = 0;
2010 flags = &localflags;
2011 }
2012 if (n) {
2013 flags->cf_flags |= iflags & PyCF_MASK;
2014 mod = PyAST_FromNode(n, flags, filename, arena);
2015 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 }
2017 else {
2018 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002019 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002021 err_free(&err);
2022 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002023}
2024
2025mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00002026PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 int start, char *ps1,
2028 char *ps2, PyCompilerFlags *flags, int *errcode,
2029 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 mod_ty mod;
2032 PyCompilerFlags localflags;
2033 perrdetail err;
2034 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
2037 &_PyParser_Grammar,
2038 start, ps1, ps2, &err, &iflags);
2039 if (flags == NULL) {
2040 localflags.cf_flags = 0;
2041 flags = &localflags;
2042 }
2043 if (n) {
2044 flags->cf_flags |= iflags & PyCF_MASK;
2045 mod = PyAST_FromNode(n, flags, filename, arena);
2046 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 }
2048 else {
2049 err_input(&err);
2050 if (errcode)
2051 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002052 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002054 err_free(&err);
2055 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002056}
2057
Guido van Rossuma110aa61994-08-29 12:50:44 +00002058/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002059
Guido van Rossuma110aa61994-08-29 12:50:44 +00002060node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002061PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 perrdetail err;
2064 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2065 &_PyParser_Grammar,
2066 start, NULL, NULL, &err, flags);
2067 if (n == NULL)
2068 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002069 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002072}
2073
Guido van Rossuma110aa61994-08-29 12:50:44 +00002074/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002075
Guido van Rossuma110aa61994-08-29 12:50:44 +00002076node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002077PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 perrdetail err;
2080 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2081 start, &err, flags);
2082 if (n == NULL)
2083 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002084 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002086}
2087
2088node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002089PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 perrdetail err;
2093 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2094 &_PyParser_Grammar, start, &err, flags);
2095 if (n == NULL)
2096 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002097 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002099}
2100
2101node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002102PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002105}
2106
Guido van Rossum66ebd912003-04-17 16:02:26 +00002107/* May want to move a more generalized form of this to parsetok.c or
2108 even parser modules. */
2109
2110void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002111PyParser_ClearError(perrdetail *err)
2112{
2113 err_free(err);
2114}
2115
2116void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002117PyParser_SetError(perrdetail *err)
2118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002120}
2121
Victor Stinner7f2fee32011-04-05 00:39:01 +02002122static void
2123err_free(perrdetail *err)
2124{
2125 Py_CLEAR(err->filename);
2126}
2127
Guido van Rossuma110aa61994-08-29 12:50:44 +00002128/* Set the error appropriate to the given input error code (see errcode.h) */
2129
2130static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002131err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 PyObject *v, *w, *errtype, *errtext;
2134 PyObject *msg_obj = NULL;
2135 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 errtype = PyExc_SyntaxError;
2138 switch (err->error) {
2139 case E_ERROR:
2140 return;
2141 case E_SYNTAX:
2142 errtype = PyExc_IndentationError;
2143 if (err->expected == INDENT)
2144 msg = "expected an indented block";
2145 else if (err->token == INDENT)
2146 msg = "unexpected indent";
2147 else if (err->token == DEDENT)
2148 msg = "unexpected unindent";
2149 else {
2150 errtype = PyExc_SyntaxError;
2151 msg = "invalid syntax";
2152 }
2153 break;
2154 case E_TOKEN:
2155 msg = "invalid token";
2156 break;
2157 case E_EOFS:
2158 msg = "EOF while scanning triple-quoted string literal";
2159 break;
2160 case E_EOLS:
2161 msg = "EOL while scanning string literal";
2162 break;
2163 case E_INTR:
2164 if (!PyErr_Occurred())
2165 PyErr_SetNone(PyExc_KeyboardInterrupt);
2166 goto cleanup;
2167 case E_NOMEM:
2168 PyErr_NoMemory();
2169 goto cleanup;
2170 case E_EOF:
2171 msg = "unexpected EOF while parsing";
2172 break;
2173 case E_TABSPACE:
2174 errtype = PyExc_TabError;
2175 msg = "inconsistent use of tabs and spaces in indentation";
2176 break;
2177 case E_OVERFLOW:
2178 msg = "expression too long";
2179 break;
2180 case E_DEDENT:
2181 errtype = PyExc_IndentationError;
2182 msg = "unindent does not match any outer indentation level";
2183 break;
2184 case E_TOODEEP:
2185 errtype = PyExc_IndentationError;
2186 msg = "too many levels of indentation";
2187 break;
2188 case E_DECODE: {
2189 PyObject *type, *value, *tb;
2190 PyErr_Fetch(&type, &value, &tb);
2191 msg = "unknown decode error";
2192 if (value != NULL)
2193 msg_obj = PyObject_Str(value);
2194 Py_XDECREF(type);
2195 Py_XDECREF(value);
2196 Py_XDECREF(tb);
2197 break;
2198 }
2199 case E_LINECONT:
2200 msg = "unexpected character after line continuation character";
2201 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 case E_IDENTIFIER:
2204 msg = "invalid character in identifier";
2205 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002206 case E_BADSINGLE:
2207 msg = "multiple statements found while compiling a single statement";
2208 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 default:
2210 fprintf(stderr, "error=%d\n", err->error);
2211 msg = "unknown parsing error";
2212 break;
2213 }
2214 /* err->text may not be UTF-8 in case of decoding errors.
2215 Explicitly convert to an object. */
2216 if (!err->text) {
2217 errtext = Py_None;
2218 Py_INCREF(Py_None);
2219 } else {
2220 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2221 "replace");
2222 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002223 v = Py_BuildValue("(OiiN)", err->filename,
2224 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 if (v != NULL) {
2226 if (msg_obj)
2227 w = Py_BuildValue("(OO)", msg_obj, v);
2228 else
2229 w = Py_BuildValue("(sO)", msg, v);
2230 } else
2231 w = NULL;
2232 Py_XDECREF(v);
2233 PyErr_SetObject(errtype, w);
2234 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002235cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 Py_XDECREF(msg_obj);
2237 if (err->text != NULL) {
2238 PyObject_FREE(err->text);
2239 err->text = NULL;
2240 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002241}
2242
2243/* Print fatal error message and abort */
2244
2245void
Tim Peters7c321a82002-07-09 02:57:01 +00002246Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002247{
Victor Stinner024e37a2011-03-31 01:31:06 +02002248 const int fd = fileno(stderr);
2249 PyThreadState *tstate;
2250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 fprintf(stderr, "Fatal Python error: %s\n", msg);
2252 fflush(stderr); /* it helps in Windows debug build */
2253 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002254 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002256 else {
2257 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2258 if (tstate != NULL) {
2259 fputc('\n', stderr);
2260 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002261 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002262 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002263 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002264 }
2265
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002266#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 {
2268 size_t len = strlen(msg);
2269 WCHAR* buffer;
2270 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 /* Convert the message to wchar_t. This uses a simple one-to-one
2273 conversion, assuming that the this error message actually uses ASCII
2274 only. If this ceases to be true, we will have to convert. */
2275 buffer = alloca( (len+1) * (sizeof *buffer));
2276 for( i=0; i<=len; ++i)
2277 buffer[i] = msg[i];
2278 OutputDebugStringW(L"Fatal Python error: ");
2279 OutputDebugStringW(buffer);
2280 OutputDebugStringW(L"\n");
2281 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002282#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002284#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002285#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002287}
2288
2289/* Clean up and exit */
2290
Guido van Rossuma110aa61994-08-29 12:50:44 +00002291#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002292#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002293#endif
2294
Collin Winter670e6922007-03-21 02:57:17 +00002295static void (*pyexitfunc)(void) = NULL;
2296/* For the atexit module. */
2297void _Py_PyAtExit(void (*func)(void))
2298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002300}
2301
2302static void
2303call_py_exitfuncs(void)
2304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 if (pyexitfunc == NULL)
2306 return;
Collin Winter670e6922007-03-21 02:57:17 +00002307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 (*pyexitfunc)();
2309 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002310}
2311
Antoine Pitrou011bd622009-10-20 21:52:47 +00002312/* Wait until threading._shutdown completes, provided
2313 the threading module was imported in the first place.
2314 The shutdown routine will wait until all non-daemon
2315 "threading" threads have completed. */
2316static void
2317wait_for_thread_shutdown(void)
2318{
2319#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002320 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 PyObject *result;
2322 PyThreadState *tstate = PyThreadState_GET();
2323 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2324 "threading");
2325 if (threading == NULL) {
2326 /* threading not imported */
2327 PyErr_Clear();
2328 return;
2329 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002330 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 if (result == NULL) {
2332 PyErr_WriteUnraisable(threading);
2333 }
2334 else {
2335 Py_DECREF(result);
2336 }
2337 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002338#endif
2339}
2340
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002341#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002342static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002343static int nexitfuncs = 0;
2344
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002345int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 if (nexitfuncs >= NEXITFUNCS)
2348 return -1;
2349 exitfuncs[nexitfuncs++] = func;
2350 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002351}
2352
Guido van Rossumcc283f51997-08-05 02:22:03 +00002353static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002354call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 while (nexitfuncs > 0)
2357 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 fflush(stdout);
2360 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002361}
2362
2363void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002364Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002369}
2370
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002371static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002372initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002373{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002374#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002376#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002377#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002379#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002380#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002382#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002384}
2385
Guido van Rossum7433b121997-02-14 19:45:36 +00002386
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002387/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2388 *
2389 * All of the code in this function must only use async-signal-safe functions,
2390 * listed at `man 7 signal` or
2391 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2392 */
2393void
2394_Py_RestoreSignals(void)
2395{
2396#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002398#endif
2399#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002401#endif
2402#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002404#endif
2405}
2406
2407
Guido van Rossum7433b121997-02-14 19:45:36 +00002408/*
2409 * The file descriptor fd is considered ``interactive'' if either
2410 * a) isatty(fd) is TRUE, or
2411 * b) the -i flag was given, and the filename associated with
2412 * the descriptor is NULL or "<stdin>" or "???".
2413 */
2414int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002415Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 if (isatty((int)fileno(fp)))
2418 return 1;
2419 if (!Py_InteractiveFlag)
2420 return 0;
2421 return (filename == NULL) ||
2422 (strcmp(filename, "<stdin>") == 0) ||
2423 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002424}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002425
2426
Tim Petersd08e3822003-04-17 15:24:21 +00002427#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002428#if defined(WIN32) && defined(_MSC_VER)
2429
2430/* Stack checking for Microsoft C */
2431
2432#include <malloc.h>
2433#include <excpt.h>
2434
Fred Drakee8de31c2000-08-31 05:38:39 +00002435/*
2436 * Return non-zero when we run out of memory on the stack; zero otherwise.
2437 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002438int
Fred Drake399739f2000-08-31 05:52:44 +00002439PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 __try {
2442 /* alloca throws a stack overflow exception if there's
2443 not enough space left on the stack */
2444 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2445 return 0;
2446 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2447 EXCEPTION_EXECUTE_HANDLER :
2448 EXCEPTION_CONTINUE_SEARCH) {
2449 int errcode = _resetstkoflw();
2450 if (errcode == 0)
2451 {
2452 Py_FatalError("Could not reset the stack!");
2453 }
2454 }
2455 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002456}
2457
2458#endif /* WIN32 && _MSC_VER */
2459
2460/* Alternate implementations can be added here... */
2461
2462#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002463
2464
2465/* Wrappers around sigaction() or signal(). */
2466
2467PyOS_sighandler_t
2468PyOS_getsig(int sig)
2469{
2470#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 struct sigaction context;
2472 if (sigaction(sig, NULL, &context) == -1)
2473 return SIG_ERR;
2474 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002475#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002477/* Special signal handling for the secure CRT in Visual Studio 2005 */
2478#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 switch (sig) {
2480 /* Only these signals are valid */
2481 case SIGINT:
2482 case SIGILL:
2483 case SIGFPE:
2484 case SIGSEGV:
2485 case SIGTERM:
2486 case SIGBREAK:
2487 case SIGABRT:
2488 break;
2489 /* Don't call signal() with other values or it will assert */
2490 default:
2491 return SIG_ERR;
2492 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002493#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 handler = signal(sig, SIG_IGN);
2495 if (handler != SIG_ERR)
2496 signal(sig, handler);
2497 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002498#endif
2499}
2500
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002501/*
2502 * All of the code in this function must only use async-signal-safe functions,
2503 * listed at `man 7 signal` or
2504 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2505 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002506PyOS_sighandler_t
2507PyOS_setsig(int sig, PyOS_sighandler_t handler)
2508{
2509#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 /* Some code in Modules/signalmodule.c depends on sigaction() being
2511 * used here if HAVE_SIGACTION is defined. Fix that if this code
2512 * changes to invalidate that assumption.
2513 */
2514 struct sigaction context, ocontext;
2515 context.sa_handler = handler;
2516 sigemptyset(&context.sa_mask);
2517 context.sa_flags = 0;
2518 if (sigaction(sig, &context, &ocontext) == -1)
2519 return SIG_ERR;
2520 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002521#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 PyOS_sighandler_t oldhandler;
2523 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002524#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002526#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002528#endif
2529}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002530
2531/* Deprecated C API functions still provided for binary compatiblity */
2532
2533#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002534PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002535PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002538}
2539
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002540#undef PyParser_SimpleParseString
2541PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002542PyParser_SimpleParseString(const char *str, int start)
2543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002545}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002546
2547#undef PyRun_AnyFile
2548PyAPI_FUNC(int)
2549PyRun_AnyFile(FILE *fp, const char *name)
2550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002552}
2553
2554#undef PyRun_AnyFileEx
2555PyAPI_FUNC(int)
2556PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002559}
2560
2561#undef PyRun_AnyFileFlags
2562PyAPI_FUNC(int)
2563PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002566}
2567
2568#undef PyRun_File
2569PyAPI_FUNC(PyObject *)
2570PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002573}
2574
2575#undef PyRun_FileEx
2576PyAPI_FUNC(PyObject *)
2577PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002580}
2581
2582#undef PyRun_FileFlags
2583PyAPI_FUNC(PyObject *)
2584PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002588}
2589
2590#undef PyRun_SimpleFile
2591PyAPI_FUNC(int)
2592PyRun_SimpleFile(FILE *f, const char *p)
2593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002595}
2596
2597#undef PyRun_SimpleFileEx
2598PyAPI_FUNC(int)
2599PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002602}
2603
2604
2605#undef PyRun_String
2606PyAPI_FUNC(PyObject *)
2607PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002610}
2611
2612#undef PyRun_SimpleString
2613PyAPI_FUNC(int)
2614PyRun_SimpleString(const char *s)
2615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002617}
2618
2619#undef Py_CompileString
2620PyAPI_FUNC(PyObject *)
2621Py_CompileString(const char *str, const char *p, int s)
2622{
Georg Brandl8334fd92010-12-04 10:26:46 +00002623 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2624}
2625
2626#undef Py_CompileStringFlags
2627PyAPI_FUNC(PyObject *)
2628Py_CompileStringFlags(const char *str, const char *p, int s,
2629 PyCompilerFlags *flags)
2630{
2631 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002632}
2633
2634#undef PyRun_InteractiveOne
2635PyAPI_FUNC(int)
2636PyRun_InteractiveOne(FILE *f, const char *p)
2637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002639}
2640
2641#undef PyRun_InteractiveLoop
2642PyAPI_FUNC(int)
2643PyRun_InteractiveLoop(FILE *f, const char *p)
2644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002646}
2647
2648#ifdef __cplusplus
2649}
2650#endif