blob: 1888fba9b97681b07f7bdbfe5aa24fbe25889346 [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);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000070extern void _PyUnicode_Init(void);
71extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020074extern int _PyFaulthandler_Init(void);
75extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000084int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000085int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020086int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000087int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000088int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000089int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000090int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000091int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000092int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000094int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000095
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020096PyThreadState *_Py_Finalizing = NULL;
97
Christian Heimes33fe8092008-04-13 13:53:33 +000098/* PyModule_GetWarningsModule is no longer necessary as of 2.6
99since _warnings is builtin. This API should not be used. */
100PyObject *
101PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000104}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000105
Guido van Rossum25ce5661997-08-02 03:10:38 +0000106static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000107
Thomas Wouters7e474022000-07-16 12:04:32 +0000108/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109
110int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000111Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000114}
115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116/* Global initializations. Can be undone by Py_Finalize(). Don't
117 call this twice without an intervening Py_Finalize() call. When
118 initializations fail, a fatal error is issued and the function does
119 not return. On return, the first thread and interpreter state have
120 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000121
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122 Locking: you must hold the interpreter lock while calling this.
123 (If the lock has not yet been initialized, that's equivalent to
124 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000125
Guido van Rossum25ce5661997-08-02 03:10:38 +0000126*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000127
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000128static int
129add_flag(int flag, const char *envs)
130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 int env = atoi(envs);
132 if (flag < env)
133 flag = env;
134 if (flag < 1)
135 flag = 1;
136 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000137}
138
Christian Heimes5833a2f2008-10-30 21:40:04 +0000139static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000140get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000141{
Victor Stinner94908bb2010-08-18 21:23:25 +0000142 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000143 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000144
Victor Stinner94908bb2010-08-18 21:23:25 +0000145 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 if (!codec)
147 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 name = PyObject_GetAttrString(codec, "name");
150 Py_CLEAR(codec);
151 if (!name)
152 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000153
Victor Stinner94908bb2010-08-18 21:23:25 +0000154 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100155 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000156 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000157 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000159 if (name_str == NULL) {
160 PyErr_NoMemory();
161 return NULL;
162 }
163 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000164
165error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000167 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000169}
Victor Stinner94908bb2010-08-18 21:23:25 +0000170
Victor Stinner94908bb2010-08-18 21:23:25 +0000171static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200172get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000173{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200174#ifdef MS_WINDOWS
175 char codepage[100];
176 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
177 return get_codec_name(codepage);
178#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000179 char* codeset = nl_langinfo(CODESET);
180 if (!codeset || codeset[0] == '\0') {
181 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
182 return NULL;
183 }
184 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200185#else
186 PyErr_SetNone(PyExc_NotImplementedError);
187 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000188#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200189}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000190
Guido van Rossuma027efa1997-05-05 20:56:21 +0000191void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000192Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 PyInterpreterState *interp;
195 PyThreadState *tstate;
196 PyObject *bimod, *sysmod, *pstderr;
197 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 if (initialized)
201 return;
202 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200203 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000204
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000205#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 /* Set up the LC_CTYPE locale, so we can obtain
207 the locale's charset without having to switch
208 locales. */
209 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000210#endif
211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
213 Py_DebugFlag = add_flag(Py_DebugFlag, p);
214 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
215 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
216 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
217 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
218 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
219 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 interp = PyInterpreterState_New();
222 if (interp == NULL)
223 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 tstate = PyThreadState_New(interp);
226 if (tstate == NULL)
227 Py_FatalError("Py_Initialize: can't make first thread");
228 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000229
Victor Stinner6961bd62010-08-17 22:26:51 +0000230#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000231 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
232 destroying the GIL might fail when it is being referenced from
233 another running thread (see issue #9901).
234 Instead we destroy the previously created GIL here, which ensures
235 that we can call Py_Initialize / Py_Finalize multiple times. */
236 _PyEval_FiniThreads();
237
238 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000239 _PyGILState_Init(interp, tstate);
240#endif /* WITH_THREAD */
241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (!_PyFrame_Init())
245 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (!_PyLong_Init())
248 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (!PyByteArray_Init())
251 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 interp->modules = PyDict_New();
256 if (interp->modules == NULL)
257 Py_FatalError("Py_Initialize: can't make modules dictionary");
258 interp->modules_reloading = PyDict_New();
259 if (interp->modules_reloading == NULL)
260 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 /* Init Unicode implementation; relies on the codec registry */
263 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 bimod = _PyBuiltin_Init();
266 if (bimod == NULL)
267 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000268 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 interp->builtins = PyModule_GetDict(bimod);
270 if (interp->builtins == NULL)
271 Py_FatalError("Py_Initialize: can't initialize builtins dict");
272 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 /* initialize builtin exceptions */
275 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 sysmod = _PySys_Init();
278 if (sysmod == NULL)
279 Py_FatalError("Py_Initialize: can't initialize sys");
280 interp->sysdict = PyModule_GetDict(sysmod);
281 if (interp->sysdict == NULL)
282 Py_FatalError("Py_Initialize: can't initialize sys dict");
283 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000284 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 PySys_SetPath(Py_GetPath());
286 PyDict_SetItemString(interp->sysdict, "modules",
287 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 /* Set up a preliminary stderr printer until we have enough
290 infrastructure for the io module in place. */
291 pstderr = PyFile_NewStdPrinter(fileno(stderr));
292 if (pstderr == NULL)
293 Py_FatalError("Py_Initialize: can't set preliminary stderr");
294 PySys_SetObject("stderr", pstderr);
295 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000296 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000301
Victor Stinner024e37a2011-03-31 01:31:06 +0200302 /* initialize the faulthandler module */
303 if (_PyFaulthandler_Init())
304 Py_FatalError("Py_Initialize: can't initialize faulthandler");
305
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000306 /* Initialize _warnings. */
307 _PyWarnings_Init();
308
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000309 _PyTime_Init();
310
Victor Stinner793b5312011-04-27 00:24:21 +0200311 if (initfsencoding(interp) < 0)
312 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (install_sigs)
315 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 initmain(); /* Module __main__ */
318 if (initstdio() < 0)
319 Py_FatalError(
320 "Py_Initialize: can't initialize sys standard streams");
321
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000322 /* Initialize warnings. */
323 if (PySys_HasWarnOptions()) {
324 PyObject *warnings_module = PyImport_ImportModule("warnings");
325 if (warnings_module == NULL) {
326 fprintf(stderr, "'import warnings' failed; traceback:\n");
327 PyErr_Print();
328 }
329 Py_XDECREF(warnings_module);
330 }
331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 if (!Py_NoSiteFlag)
333 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000334}
335
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000336void
337Py_Initialize(void)
338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000340}
341
342
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000343#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000344extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000345#endif
346
Guido van Rossume8432ac2007-07-09 15:04:50 +0000347/* Flush stdout and stderr */
348
Neal Norwitz2bad9702007-08-27 06:19:22 +0000349static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000350flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 PyObject *fout = PySys_GetObject("stdout");
353 PyObject *ferr = PySys_GetObject("stderr");
354 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 if (fout != NULL && fout != Py_None) {
357 tmp = PyObject_CallMethod(fout, "flush", "");
358 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000359 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 else
361 Py_DECREF(tmp);
362 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000363
Victor Stinner9467b212010-05-14 00:59:09 +0000364 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 tmp = PyObject_CallMethod(ferr, "flush", "");
366 if (tmp == NULL)
367 PyErr_Clear();
368 else
369 Py_DECREF(tmp);
370 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000371}
372
Guido van Rossum25ce5661997-08-02 03:10:38 +0000373/* Undo the effect of Py_Initialize().
374
375 Beware: if multiple interpreter and/or thread states exist, these
376 are not wiped out; only the current thread and interpreter state
377 are deleted. But since everything else is deleted, those other
378 interpreter and thread states should no longer be used.
379
380 (XXX We should do better, e.g. wipe out all interpreters and
381 threads.)
382
383 Locking: as above.
384
385*/
386
387void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000388Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 PyInterpreterState *interp;
391 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 if (!initialized)
394 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 /* The interpreter is still entirely intact at this point, and the
399 * exit funcs may be relying on that. In particular, if some thread
400 * or exit func is still waiting to do an import, the import machinery
401 * expects Py_IsInitialized() to return true. So don't say the
402 * interpreter is uninitialized until after the exit funcs have run.
403 * Note that Threading.py uses an exit func to do a join on all the
404 * threads created thru it, so this also protects pending imports in
405 * the threads created via Threading.
406 */
407 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 /* Get current thread state and interpreter pointer */
410 tstate = PyThreadState_GET();
411 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000412
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200413 /* Remaining threads (e.g. daemon threads) will automatically exit
414 after taking the GIL (in PyEval_RestoreThread()). */
415 _Py_Finalizing = tstate;
416 initialized = 0;
417
418 /* Flush stdout+stderr */
419 flush_std_files();
420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 /* Disable signal handling */
422 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 /* Clear type lookup cache */
425 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 /* Collect garbage. This may call finalizers; it's nice to call these
428 * before all modules are destroyed.
429 * XXX If a __del__ or weakref callback is triggered here, and tries to
430 * XXX import a module, bad things can happen, because Python no
431 * XXX longer believes it's initialized.
432 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
433 * XXX is easy to provoke that way. I've also seen, e.g.,
434 * XXX Exception exceptions.ImportError: 'No module named sha'
435 * XXX in <function callback at 0x008F5718> ignored
436 * XXX but I'm unclear on exactly how that one happens. In any case,
437 * XXX I haven't seen a real-life report of either of these.
438 */
439 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000440#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 /* With COUNT_ALLOCS, it helps to run GC multiple times:
442 each collection might release some types from the type
443 list, so they become garbage. */
444 while (PyGC_Collect() > 0)
445 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000446#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000447 /* We run this while most interpreter state is still alive, so that
448 debug information can be printed out */
449 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 /* Destroy all modules */
452 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* Flush stdout+stderr (again, in case more was printed) */
455 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* Collect final garbage. This disposes of cycles created by
458 * new-style class definitions, for example.
459 * XXX This is disabled because it caused too many problems. If
460 * XXX a __del__ or weakref callback triggers here, Python code has
461 * XXX a hard time running, because even the sys module has been
462 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
463 * XXX One symptom is a sequence of information-free messages
464 * XXX coming from threads (if a __del__ or callback is invoked,
465 * XXX other threads can execute too, and any exception they encounter
466 * XXX triggers a comedy of errors as subsystem after subsystem
467 * XXX fails to find what it *expects* to find in sys to help report
468 * XXX the exception and consequent unexpected failures). I've also
469 * XXX seen segfaults then, after adding print statements to the
470 * XXX Python code getting called.
471 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000472#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000474#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
477 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000478
Victor Stinner024e37a2011-03-31 01:31:06 +0200479 /* unload faulthandler module */
480 _PyFaulthandler_Fini();
481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000483#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000485#endif
486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000488
Tim Peters9cf25ce2003-04-17 15:21:01 +0000489#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* Display all objects still alive -- this can invoke arbitrary
491 * __repr__ overrides, so requires a mostly-intact interpreter.
492 * Alas, a lot of stuff may still be alive now that will be cleaned
493 * up later.
494 */
495 if (Py_GETENV("PYTHONDUMPREFS"))
496 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000497#endif /* Py_TRACE_REFS */
498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 /* Clear interpreter state */
500 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 /* Now we decref the exception classes. After this point nothing
503 can raise an exception. That's okay, because each Fini() method
504 below has been checked to make sure no exceptions are ever
505 raised.
506 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000511#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000513#endif /* WITH_THREAD */
514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 /* Delete current thread */
516 PyThreadState_Swap(NULL);
517 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 /* Sundry finalizers */
520 PyMethod_Fini();
521 PyFrame_Fini();
522 PyCFunction_Fini();
523 PyTuple_Fini();
524 PyList_Fini();
525 PySet_Fini();
526 PyBytes_Fini();
527 PyByteArray_Fini();
528 PyLong_Fini();
529 PyFloat_Fini();
530 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 /* Cleanup Unicode implementation */
533 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000536 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 free((char*)Py_FileSystemDefaultEncoding);
538 Py_FileSystemDefaultEncoding = NULL;
539 }
Christian Heimesc8967002007-11-30 10:18:26 +0000540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 /* XXX Still allocated:
542 - various static ad-hoc pointers to interned strings
543 - int and float free list blocks
544 - whatever various modules and libraries allocate
545 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000548
Tim Peters269b2a62003-04-17 19:52:29 +0000549#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 /* Display addresses (& refcnts) of all objects still alive.
551 * An address can be used to find the repr of the object, printed
552 * above by _Py_PrintReferences.
553 */
554 if (Py_GETENV("PYTHONDUMPREFS"))
555 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000556#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000557#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if (Py_GETENV("PYTHONMALLOCSTATS"))
559 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000560#endif
561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000563}
564
565/* Create and initialize a new interpreter and thread, and return the
566 new thread. This requires that Py_Initialize() has been called
567 first.
568
569 Unsuccessful initialization yields a NULL pointer. Note that *no*
570 exception information is available even in this case -- the
571 exception information is held in the thread, and there is no
572 thread.
573
574 Locking: as above.
575
576*/
577
578PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000579Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 PyInterpreterState *interp;
582 PyThreadState *tstate, *save_tstate;
583 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 if (!initialized)
586 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 interp = PyInterpreterState_New();
589 if (interp == NULL)
590 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 tstate = PyThreadState_New(interp);
593 if (tstate == NULL) {
594 PyInterpreterState_Delete(interp);
595 return NULL;
596 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 interp->modules = PyDict_New();
603 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000604
Victor Stinner49d3f252010-10-17 01:24:53 +0000605 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (bimod != NULL) {
607 interp->builtins = PyModule_GetDict(bimod);
608 if (interp->builtins == NULL)
609 goto handle_error;
610 Py_INCREF(interp->builtins);
611 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 /* initialize builtin exceptions */
614 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000615
Victor Stinner49d3f252010-10-17 01:24:53 +0000616 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (bimod != NULL && sysmod != NULL) {
618 PyObject *pstderr;
619 interp->sysdict = PyModule_GetDict(sysmod);
620 if (interp->sysdict == NULL)
621 goto handle_error;
622 Py_INCREF(interp->sysdict);
623 PySys_SetPath(Py_GetPath());
624 PyDict_SetItemString(interp->sysdict, "modules",
625 interp->modules);
626 /* Set up a preliminary stderr printer until we have enough
627 infrastructure for the io module in place. */
628 pstderr = PyFile_NewStdPrinter(fileno(stderr));
629 if (pstderr == NULL)
630 Py_FatalError("Py_Initialize: can't set preliminary stderr");
631 PySys_SetObject("stderr", pstderr);
632 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000633 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200636
637 if (initfsencoding(interp) < 0)
638 goto handle_error;
639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (initstdio() < 0)
641 Py_FatalError(
642 "Py_Initialize: can't initialize sys standard streams");
643 initmain();
644 if (!Py_NoSiteFlag)
645 initsite();
646 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 if (!PyErr_Occurred())
649 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000650
Thomas Wouters89f507f2006-12-13 04:49:30 +0000651handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000653
Victor Stinnerc40a3502011-04-27 00:20:27 +0200654 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 PyThreadState_Clear(tstate);
656 PyThreadState_Swap(save_tstate);
657 PyThreadState_Delete(tstate);
658 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661}
662
663/* Delete an interpreter and its last thread. This requires that the
664 given thread state is current, that the thread has no remaining
665 frames, and that it is its interpreter's only remaining thread.
666 It is a fatal error to violate these constraints.
667
668 (Py_Finalize() doesn't have these constraints -- it zaps
669 everything, regardless.)
670
671 Locking: as above.
672
673*/
674
675void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000676Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 if (tstate != PyThreadState_GET())
681 Py_FatalError("Py_EndInterpreter: thread is not current");
682 if (tstate->frame != NULL)
683 Py_FatalError("Py_EndInterpreter: thread still has a frame");
684 if (tstate != interp->tstate_head || tstate->next != NULL)
685 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyImport_Cleanup();
688 PyInterpreterState_Clear(interp);
689 PyThreadState_Swap(NULL);
690 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000691}
692
Martin v. Löwis790465f2008-04-05 20:41:37 +0000693static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000694
695void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000696Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (pn && *pn)
699 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000700}
701
Martin v. Löwis790465f2008-04-05 20:41:37 +0000702wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000703Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000706}
707
Martin v. Löwis790465f2008-04-05 20:41:37 +0000708static wchar_t *default_home = NULL;
709static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000710
711void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000712Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000715}
716
Martin v. Löwis790465f2008-04-05 20:41:37 +0000717wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000718Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 wchar_t *home = default_home;
721 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
722 char* chome = Py_GETENV("PYTHONHOME");
723 if (chome) {
724 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
725 if (r != (size_t)-1 && r <= PATH_MAX)
726 home = env_home;
727 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 }
730 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000731}
732
Guido van Rossum6135a871995-01-09 17:53:26 +0000733/* Create __main__ module */
734
735static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000736initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 PyObject *m, *d;
739 m = PyImport_AddModule("__main__");
740 if (m == NULL)
741 Py_FatalError("can't create __main__ module");
742 d = PyModule_GetDict(m);
743 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
744 PyObject *bimod = PyImport_ImportModule("builtins");
745 if (bimod == NULL ||
746 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
747 Py_FatalError("can't add __builtins__ to __main__");
748 Py_DECREF(bimod);
749 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000750}
751
Victor Stinner793b5312011-04-27 00:24:21 +0200752static int
753initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000754{
755 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000756
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200757 if (Py_FileSystemDefaultEncoding == NULL)
758 {
759 Py_FileSystemDefaultEncoding = get_locale_encoding();
760 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000761 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000762
Victor Stinnere4743092010-10-19 00:05:51 +0000763 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200764 interp->fscodec_initialized = 1;
765 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000766 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000767
768 /* the encoding is mbcs, utf-8 or ascii */
769 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
770 if (!codec) {
771 /* Such error can only occurs in critical situations: no more
772 * memory, import a module of the standard library failed,
773 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200774 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000775 }
Victor Stinner793b5312011-04-27 00:24:21 +0200776 Py_DECREF(codec);
777 interp->fscodec_initialized = 1;
778 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000779}
780
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000781/* Import the site module (not into __main__ though) */
782
783static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000784initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyObject *m;
787 m = PyImport_ImportModule("site");
788 if (m == NULL) {
789 PyErr_Print();
790 Py_Finalize();
791 exit(1);
792 }
793 else {
794 Py_DECREF(m);
795 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000796}
797
Antoine Pitrou05608432009-01-09 18:53:14 +0000798static PyObject*
799create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 int fd, int write_mode, char* name,
801 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
804 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000805 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyObject *line_buffering;
807 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 /* stdin is always opened in buffered mode, first because it shouldn't
810 make a difference in common use cases, second because TextIOWrapper
811 depends on the presence of a read1() method which only exists on
812 buffered streams.
813 */
814 if (Py_UnbufferedStdioFlag && write_mode)
815 buffering = 0;
816 else
817 buffering = -1;
818 if (write_mode)
819 mode = "wb";
820 else
821 mode = "rb";
822 buf = PyObject_CallMethod(io, "open", "isiOOOi",
823 fd, mode, buffering,
824 Py_None, Py_None, Py_None, 0);
825 if (buf == NULL)
826 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (buffering) {
829 raw = PyObject_GetAttrString(buf, "raw");
830 if (raw == NULL)
831 goto error;
832 }
833 else {
834 raw = buf;
835 Py_INCREF(raw);
836 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 text = PyUnicode_FromString(name);
839 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
840 goto error;
841 res = PyObject_CallMethod(raw, "isatty", "");
842 if (res == NULL)
843 goto error;
844 isatty = PyObject_IsTrue(res);
845 Py_DECREF(res);
846 if (isatty == -1)
847 goto error;
848 if (isatty || Py_UnbufferedStdioFlag)
849 line_buffering = Py_True;
850 else
851 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 Py_CLEAR(raw);
854 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000855
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000856 newline = "\n";
857#ifdef MS_WINDOWS
858 if (!write_mode) {
859 /* translate \r\n to \n for sys.stdin on Windows */
860 newline = NULL;
861 }
862#endif
863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
865 buf, encoding, errors,
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000866 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 Py_CLEAR(buf);
868 if (stream == NULL)
869 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (write_mode)
872 mode = "w";
873 else
874 mode = "r";
875 text = PyUnicode_FromString(mode);
876 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
877 goto error;
878 Py_CLEAR(text);
879 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000880
881error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 Py_XDECREF(buf);
883 Py_XDECREF(stream);
884 Py_XDECREF(text);
885 Py_XDECREF(raw);
886 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000887}
888
Georg Brandl1a3284e2007-12-02 09:40:06 +0000889/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000890static int
891initstdio(void)
892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 PyObject *iomod = NULL, *wrapper;
894 PyObject *bimod = NULL;
895 PyObject *m;
896 PyObject *std = NULL;
897 int status = 0, fd;
898 PyObject * encoding_attr;
899 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 /* Hack to avoid a nasty recursion issue when Python is invoked
902 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
903 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
904 goto error;
905 }
906 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
909 goto error;
910 }
911 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (!(bimod = PyImport_ImportModule("builtins"))) {
914 goto error;
915 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 if (!(iomod = PyImport_ImportModule("io"))) {
918 goto error;
919 }
920 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
921 goto error;
922 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Set builtins.open */
925 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000926 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 goto error;
928 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000929 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 encoding = Py_GETENV("PYTHONIOENCODING");
932 errors = NULL;
933 if (encoding) {
934 encoding = strdup(encoding);
935 errors = strchr(encoding, ':');
936 if (errors) {
937 *errors = '\0';
938 errors++;
939 }
940 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Set sys.stdin */
943 fd = fileno(stdin);
944 /* Under some conditions stdin, stdout and stderr may not be connected
945 * and fileno() may point to an invalid file descriptor. For example
946 * GUI apps don't have valid standard streams by default.
947 */
948 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000949#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 std = Py_None;
951 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000952#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000954#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 }
956 else {
957 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
958 if (std == NULL)
959 goto error;
960 } /* if (fd < 0) */
961 PySys_SetObject("__stdin__", std);
962 PySys_SetObject("stdin", std);
963 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 /* Set sys.stdout */
966 fd = fileno(stdout);
967 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000968#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 std = Py_None;
970 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000971#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000973#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 }
975 else {
976 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
977 if (std == NULL)
978 goto error;
979 } /* if (fd < 0) */
980 PySys_SetObject("__stdout__", std);
981 PySys_SetObject("stdout", std);
982 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000983
Guido van Rossum98297ee2007-11-06 21:34:58 +0000984#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 /* Set sys.stderr, replaces the preliminary stderr */
986 fd = fileno(stderr);
987 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000988#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 std = Py_None;
990 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000991#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000993#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 }
995 else {
996 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
997 if (std == NULL)
998 goto error;
999 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 /* Same as hack above, pre-import stderr's codec to avoid recursion
1002 when import.c tries to write to stderr in verbose mode. */
1003 encoding_attr = PyObject_GetAttrString(std, "encoding");
1004 if (encoding_attr != NULL) {
1005 const char * encoding;
1006 encoding = _PyUnicode_AsString(encoding_attr);
1007 if (encoding != NULL) {
1008 _PyCodec_Lookup(encoding);
1009 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001010 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 }
1012 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 PySys_SetObject("__stderr__", std);
1015 PySys_SetObject("stderr", std);
1016 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001017#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001020 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 status = -1;
1022 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 if (encoding)
1025 free(encoding);
1026 Py_XDECREF(bimod);
1027 Py_XDECREF(iomod);
1028 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001029}
1030
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001031/* Parse input from a file and execute it */
1032
1033int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001034PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 if (filename == NULL)
1038 filename = "???";
1039 if (Py_FdIsInteractive(fp, filename)) {
1040 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1041 if (closeit)
1042 fclose(fp);
1043 return err;
1044 }
1045 else
1046 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001047}
1048
1049int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001050PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 PyObject *v;
1053 int ret;
1054 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (flags == NULL) {
1057 flags = &local_flags;
1058 local_flags.cf_flags = 0;
1059 }
1060 v = PySys_GetObject("ps1");
1061 if (v == NULL) {
1062 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1063 Py_XDECREF(v);
1064 }
1065 v = PySys_GetObject("ps2");
1066 if (v == NULL) {
1067 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1068 Py_XDECREF(v);
1069 }
1070 for (;;) {
1071 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1072 PRINT_TOTAL_REFS();
1073 if (ret == E_EOF)
1074 return 0;
1075 /*
1076 if (ret == E_NOMEM)
1077 return -1;
1078 */
1079 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001080}
1081
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001082/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001083static int PARSER_FLAGS(PyCompilerFlags *flags)
1084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 int parser_flags = 0;
1086 if (!flags)
1087 return 0;
1088 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1089 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1090 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1091 parser_flags |= PyPARSE_IGNORE_COOKIE;
1092 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1093 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1094 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001095}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001096
Thomas Wouters89f507f2006-12-13 04:49:30 +00001097#if 0
1098/* Keep an example of flags with future keyword support. */
1099#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1101 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1102 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1103 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001104#endif
1105
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001106int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001107PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyObject *m, *d, *v, *w, *oenc = NULL;
1110 mod_ty mod;
1111 PyArena *arena;
1112 char *ps1 = "", *ps2 = "", *enc = NULL;
1113 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (fp == stdin) {
1116 /* Fetch encoding from sys.stdin */
1117 v = PySys_GetObject("stdin");
1118 if (v == NULL || v == Py_None)
1119 return -1;
1120 oenc = PyObject_GetAttrString(v, "encoding");
1121 if (!oenc)
1122 return -1;
1123 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001124 if (enc == NULL)
1125 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 }
1127 v = PySys_GetObject("ps1");
1128 if (v != NULL) {
1129 v = PyObject_Str(v);
1130 if (v == NULL)
1131 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001132 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001134 if (ps1 == NULL) {
1135 PyErr_Clear();
1136 ps1 = "";
1137 }
1138 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 }
1140 w = PySys_GetObject("ps2");
1141 if (w != NULL) {
1142 w = PyObject_Str(w);
1143 if (w == NULL)
1144 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001145 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001147 if (ps2 == NULL) {
1148 PyErr_Clear();
1149 ps2 = "";
1150 }
1151 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 }
1153 arena = PyArena_New();
1154 if (arena == NULL) {
1155 Py_XDECREF(v);
1156 Py_XDECREF(w);
1157 Py_XDECREF(oenc);
1158 return -1;
1159 }
1160 mod = PyParser_ASTFromFile(fp, filename, enc,
1161 Py_single_input, ps1, ps2,
1162 flags, &errcode, arena);
1163 Py_XDECREF(v);
1164 Py_XDECREF(w);
1165 Py_XDECREF(oenc);
1166 if (mod == NULL) {
1167 PyArena_Free(arena);
1168 if (errcode == E_EOF) {
1169 PyErr_Clear();
1170 return E_EOF;
1171 }
1172 PyErr_Print();
1173 return -1;
1174 }
1175 m = PyImport_AddModule("__main__");
1176 if (m == NULL) {
1177 PyArena_Free(arena);
1178 return -1;
1179 }
1180 d = PyModule_GetDict(m);
1181 v = run_mod(mod, filename, d, d, flags, arena);
1182 PyArena_Free(arena);
1183 flush_io();
1184 if (v == NULL) {
1185 PyErr_Print();
1186 return -1;
1187 }
1188 Py_DECREF(v);
1189 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001190}
1191
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001192/* Check whether a file maybe a pyc file: Look at the extension,
1193 the file type, and, if we may close it, at the first few bytes. */
1194
1195static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001196maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1199 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 /* Only look into the file if we are allowed to close it, since
1202 it then should also be seekable. */
1203 if (closeit) {
1204 /* Read only two bytes of the magic. If the file was opened in
1205 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1206 be read as they are on disk. */
1207 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1208 unsigned char buf[2];
1209 /* Mess: In case of -x, the stream is NOT at its start now,
1210 and ungetc() was used to push back the first newline,
1211 which makes the current stream position formally undefined,
1212 and a x-platform nightmare.
1213 Unfortunately, we have no direct way to know whether -x
1214 was specified. So we use a terrible hack: if the current
1215 stream position is not 0, we assume -x was specified, and
1216 give up. Bug 132850 on SourceForge spells out the
1217 hopelessness of trying anything else (fseek and ftell
1218 don't work predictably x-platform for text-mode files).
1219 */
1220 int ispyc = 0;
1221 if (ftell(fp) == 0) {
1222 if (fread(buf, 1, 2, fp) == 2 &&
1223 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1224 ispyc = 1;
1225 rewind(fp);
1226 }
1227 return ispyc;
1228 }
1229 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001230}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001231
Guido van Rossum0df002c2000-08-27 19:21:52 +00001232int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001233PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 PyObject *m, *d, *v;
1237 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001238 int set_file_name = 0, ret;
1239 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 m = PyImport_AddModule("__main__");
1242 if (m == NULL)
1243 return -1;
1244 d = PyModule_GetDict(m);
1245 if (PyDict_GetItemString(d, "__file__") == NULL) {
1246 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001247 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (f == NULL)
1249 return -1;
1250 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1251 Py_DECREF(f);
1252 return -1;
1253 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001254 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1255 Py_DECREF(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 return -1;
Barry Warsaw916048d2011-09-20 14:45:44 -04001257 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 set_file_name = 1;
1259 Py_DECREF(f);
1260 }
1261 len = strlen(filename);
1262 ext = filename + len - (len > 4 ? 4 : 0);
1263 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1264 /* Try to run a pyc file. First, re-open in binary */
1265 if (closeit)
1266 fclose(fp);
1267 if ((fp = fopen(filename, "rb")) == NULL) {
1268 fprintf(stderr, "python: Can't reopen .pyc file\n");
1269 ret = -1;
1270 goto done;
1271 }
1272 /* Turn on optimization if a .pyo file is given */
1273 if (strcmp(ext, ".pyo") == 0)
1274 Py_OptimizeFlag = 1;
1275 v = run_pyc_file(fp, filename, d, d, flags);
1276 } else {
1277 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1278 closeit, flags);
1279 }
1280 flush_io();
1281 if (v == NULL) {
1282 PyErr_Print();
1283 ret = -1;
1284 goto done;
1285 }
1286 Py_DECREF(v);
1287 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001288 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1290 PyErr_Clear();
1291 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001292}
1293
1294int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001295PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 PyObject *m, *d, *v;
1298 m = PyImport_AddModule("__main__");
1299 if (m == NULL)
1300 return -1;
1301 d = PyModule_GetDict(m);
1302 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1303 if (v == NULL) {
1304 PyErr_Print();
1305 return -1;
1306 }
1307 Py_DECREF(v);
1308 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001309}
1310
Barry Warsaw035574d1997-08-29 22:07:17 +00001311static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001312parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 long hold;
1316 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 /* old style errors */
1319 if (PyTuple_Check(err))
1320 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1321 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (! (v = PyObject_GetAttrString(err, "msg")))
1326 goto finally;
1327 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 if (!(v = PyObject_GetAttrString(err, "filename")))
1330 goto finally;
1331 if (v == Py_None)
1332 *filename = NULL;
1333 else if (! (*filename = _PyUnicode_AsString(v)))
1334 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 Py_DECREF(v);
1337 if (!(v = PyObject_GetAttrString(err, "lineno")))
1338 goto finally;
1339 hold = PyLong_AsLong(v);
1340 Py_DECREF(v);
1341 v = NULL;
1342 if (hold < 0 && PyErr_Occurred())
1343 goto finally;
1344 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 if (!(v = PyObject_GetAttrString(err, "offset")))
1347 goto finally;
1348 if (v == Py_None) {
1349 *offset = -1;
1350 Py_DECREF(v);
1351 v = NULL;
1352 } else {
1353 hold = PyLong_AsLong(v);
1354 Py_DECREF(v);
1355 v = NULL;
1356 if (hold < 0 && PyErr_Occurred())
1357 goto finally;
1358 *offset = (int)hold;
1359 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 if (!(v = PyObject_GetAttrString(err, "text")))
1362 goto finally;
1363 if (v == Py_None)
1364 *text = NULL;
1365 else if (!PyUnicode_Check(v) ||
1366 !(*text = _PyUnicode_AsString(v)))
1367 goto finally;
1368 Py_DECREF(v);
1369 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001370
1371finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 Py_XDECREF(v);
1373 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001374}
1375
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001376void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001377PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001380}
1381
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001382static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001383print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 char *nl;
1386 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001387 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1388 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 for (;;) {
1390 nl = strchr(text, '\n');
1391 if (nl == NULL || nl-text >= offset)
1392 break;
1393 offset -= (int)(nl+1-text);
1394 text = nl+1;
1395 }
1396 while (*text == ' ' || *text == '\t') {
1397 text++;
1398 offset--;
1399 }
1400 }
1401 PyFile_WriteString(" ", f);
1402 PyFile_WriteString(text, f);
1403 if (*text == '\0' || text[strlen(text)-1] != '\n')
1404 PyFile_WriteString("\n", f);
1405 if (offset == -1)
1406 return;
1407 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001408 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001411}
1412
Guido van Rossum66e8e862001-03-23 17:54:43 +00001413static void
1414handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 PyObject *exception, *value, *tb;
1417 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (Py_InspectFlag)
1420 /* Don't exit if -i flag was given. This flag is set to 0
1421 * when entering interactive mode for inspecting. */
1422 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 PyErr_Fetch(&exception, &value, &tb);
1425 fflush(stdout);
1426 if (value == NULL || value == Py_None)
1427 goto done;
1428 if (PyExceptionInstance_Check(value)) {
1429 /* The error code should be in the `code' attribute. */
1430 PyObject *code = PyObject_GetAttrString(value, "code");
1431 if (code) {
1432 Py_DECREF(value);
1433 value = code;
1434 if (value == Py_None)
1435 goto done;
1436 }
1437 /* If we failed to dig out the 'code' attribute,
1438 just let the else clause below print the error. */
1439 }
1440 if (PyLong_Check(value))
1441 exitcode = (int)PyLong_AsLong(value);
1442 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001443 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001444 if (sys_stderr != NULL && sys_stderr != Py_None) {
1445 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1446 } else {
1447 PyObject_Print(value, stderr, Py_PRINT_RAW);
1448 fflush(stderr);
1449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 PySys_WriteStderr("\n");
1451 exitcode = 1;
1452 }
Tim Peterscf615b52003-04-19 18:47:02 +00001453 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 /* Restore and clear the exception info, in order to properly decref
1455 * the exception, value, and traceback. If we just exit instead,
1456 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1457 * some finalizers from running.
1458 */
1459 PyErr_Restore(exception, value, tb);
1460 PyErr_Clear();
1461 Py_Exit(exitcode);
1462 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001463}
1464
1465void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001466PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1471 handle_system_exit();
1472 }
1473 PyErr_Fetch(&exception, &v, &tb);
1474 if (exception == NULL)
1475 return;
1476 PyErr_NormalizeException(&exception, &v, &tb);
1477 if (tb == NULL) {
1478 tb = Py_None;
1479 Py_INCREF(tb);
1480 }
1481 PyException_SetTraceback(v, tb);
1482 if (exception == NULL)
1483 return;
1484 /* Now we know v != NULL too */
1485 if (set_sys_last_vars) {
1486 PySys_SetObject("last_type", exception);
1487 PySys_SetObject("last_value", v);
1488 PySys_SetObject("last_traceback", tb);
1489 }
1490 hook = PySys_GetObject("excepthook");
1491 if (hook) {
1492 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1493 PyObject *result = PyEval_CallObject(hook, args);
1494 if (result == NULL) {
1495 PyObject *exception2, *v2, *tb2;
1496 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1497 handle_system_exit();
1498 }
1499 PyErr_Fetch(&exception2, &v2, &tb2);
1500 PyErr_NormalizeException(&exception2, &v2, &tb2);
1501 /* It should not be possible for exception2 or v2
1502 to be NULL. However PyErr_Display() can't
1503 tolerate NULLs, so just be safe. */
1504 if (exception2 == NULL) {
1505 exception2 = Py_None;
1506 Py_INCREF(exception2);
1507 }
1508 if (v2 == NULL) {
1509 v2 = Py_None;
1510 Py_INCREF(v2);
1511 }
1512 fflush(stdout);
1513 PySys_WriteStderr("Error in sys.excepthook:\n");
1514 PyErr_Display(exception2, v2, tb2);
1515 PySys_WriteStderr("\nOriginal exception was:\n");
1516 PyErr_Display(exception, v, tb);
1517 Py_DECREF(exception2);
1518 Py_DECREF(v2);
1519 Py_XDECREF(tb2);
1520 }
1521 Py_XDECREF(result);
1522 Py_XDECREF(args);
1523 } else {
1524 PySys_WriteStderr("sys.excepthook is missing\n");
1525 PyErr_Display(exception, v, tb);
1526 }
1527 Py_XDECREF(exception);
1528 Py_XDECREF(v);
1529 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001530}
1531
Benjamin Petersone6528212008-07-15 15:32:09 +00001532static void
1533print_exception(PyObject *f, PyObject *value)
1534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 int err = 0;
1536 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 if (!PyExceptionInstance_Check(value)) {
1539 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1540 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1541 PyFile_WriteString(" found\n", f);
1542 return;
1543 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 Py_INCREF(value);
1546 fflush(stdout);
1547 type = (PyObject *) Py_TYPE(value);
1548 tb = PyException_GetTraceback(value);
1549 if (tb && tb != Py_None)
1550 err = PyTraceBack_Print(tb, f);
1551 if (err == 0 &&
1552 PyObject_HasAttrString(value, "print_file_and_line"))
1553 {
1554 PyObject *message;
1555 const char *filename, *text;
1556 int lineno, offset;
1557 if (!parse_syntax_error(value, &message, &filename,
1558 &lineno, &offset, &text))
1559 PyErr_Clear();
1560 else {
1561 char buf[10];
1562 PyFile_WriteString(" File \"", f);
1563 if (filename == NULL)
1564 PyFile_WriteString("<string>", f);
1565 else
1566 PyFile_WriteString(filename, f);
1567 PyFile_WriteString("\", line ", f);
1568 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1569 PyFile_WriteString(buf, f);
1570 PyFile_WriteString("\n", f);
1571 if (text != NULL)
1572 print_error_text(f, offset, text);
1573 Py_DECREF(value);
1574 value = message;
1575 /* Can't be bothered to check all those
1576 PyFile_WriteString() calls */
1577 if (PyErr_Occurred())
1578 err = -1;
1579 }
1580 }
1581 if (err) {
1582 /* Don't do anything else */
1583 }
1584 else {
1585 PyObject* moduleName;
1586 char* className;
1587 assert(PyExceptionClass_Check(type));
1588 className = PyExceptionClass_Name(type);
1589 if (className != NULL) {
1590 char *dot = strrchr(className, '.');
1591 if (dot != NULL)
1592 className = dot+1;
1593 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 moduleName = PyObject_GetAttrString(type, "__module__");
1596 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1597 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001598 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 err = PyFile_WriteString("<unknown>", f);
1600 }
1601 else {
1602 char* modstr = _PyUnicode_AsString(moduleName);
1603 if (modstr && strcmp(modstr, "builtins"))
1604 {
1605 err = PyFile_WriteString(modstr, f);
1606 err += PyFile_WriteString(".", f);
1607 }
1608 Py_DECREF(moduleName);
1609 }
1610 if (err == 0) {
1611 if (className == NULL)
1612 err = PyFile_WriteString("<unknown>", f);
1613 else
1614 err = PyFile_WriteString(className, f);
1615 }
1616 }
1617 if (err == 0 && (value != Py_None)) {
1618 PyObject *s = PyObject_Str(value);
1619 /* only print colon if the str() of the
1620 object is not the empty string
1621 */
1622 if (s == NULL)
1623 err = -1;
1624 else if (!PyUnicode_Check(s) ||
1625 PyUnicode_GetSize(s) != 0)
1626 err = PyFile_WriteString(": ", f);
1627 if (err == 0)
1628 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1629 Py_XDECREF(s);
1630 }
1631 /* try to write a newline in any case */
1632 err += PyFile_WriteString("\n", f);
1633 Py_XDECREF(tb);
1634 Py_DECREF(value);
1635 /* If an error happened here, don't show it.
1636 XXX This is wrong, but too many callers rely on this behavior. */
1637 if (err != 0)
1638 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001639}
1640
1641static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 "\nThe above exception was the direct cause "
1643 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001644
1645static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 "\nDuring handling of the above exception, "
1647 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001648
1649static void
1650print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 int err = 0, res;
1653 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 if (seen != NULL) {
1656 /* Exception chaining */
1657 if (PySet_Add(seen, value) == -1)
1658 PyErr_Clear();
1659 else if (PyExceptionInstance_Check(value)) {
1660 cause = PyException_GetCause(value);
1661 context = PyException_GetContext(value);
1662 if (cause) {
1663 res = PySet_Contains(seen, cause);
1664 if (res == -1)
1665 PyErr_Clear();
1666 if (res == 0) {
1667 print_exception_recursive(
1668 f, cause, seen);
1669 err |= PyFile_WriteString(
1670 cause_message, f);
1671 }
1672 }
1673 else if (context) {
1674 res = PySet_Contains(seen, context);
1675 if (res == -1)
1676 PyErr_Clear();
1677 if (res == 0) {
1678 print_exception_recursive(
1679 f, context, seen);
1680 err |= PyFile_WriteString(
1681 context_message, f);
1682 }
1683 }
1684 Py_XDECREF(context);
1685 Py_XDECREF(cause);
1686 }
1687 }
1688 print_exception(f, value);
1689 if (err != 0)
1690 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001691}
1692
Thomas Wouters477c8d52006-05-27 19:21:47 +00001693void
1694PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 PyObject *seen;
1697 PyObject *f = PySys_GetObject("stderr");
1698 if (f == Py_None) {
1699 /* pass */
1700 }
1701 else if (f == NULL) {
1702 _PyObject_Dump(value);
1703 fprintf(stderr, "lost sys.stderr\n");
1704 }
1705 else {
1706 /* We choose to ignore seen being possibly NULL, and report
1707 at least the main exception (it could be a MemoryError).
1708 */
1709 seen = PySet_New(NULL);
1710 if (seen == NULL)
1711 PyErr_Clear();
1712 print_exception_recursive(f, value, seen);
1713 Py_XDECREF(seen);
1714 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001715}
1716
Guido van Rossum82598051997-03-05 00:20:32 +00001717PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001718PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 PyObject *ret = NULL;
1722 mod_ty mod;
1723 PyArena *arena = PyArena_New();
1724 if (arena == NULL)
1725 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1728 if (mod != NULL)
1729 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1730 PyArena_Free(arena);
1731 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001732}
1733
1734PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001735PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 PyObject *ret;
1739 mod_ty mod;
1740 PyArena *arena = PyArena_New();
1741 if (arena == NULL)
1742 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1745 flags, NULL, arena);
1746 if (closeit)
1747 fclose(fp);
1748 if (mod == NULL) {
1749 PyArena_Free(arena);
1750 return NULL;
1751 }
1752 ret = run_mod(mod, filename, globals, locals, flags, arena);
1753 PyArena_Free(arena);
1754 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001755}
1756
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001757static void
1758flush_io(void)
1759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 PyObject *f, *r;
1761 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 /* Save the current exception */
1764 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 f = PySys_GetObject("stderr");
1767 if (f != NULL) {
1768 r = PyObject_CallMethod(f, "flush", "");
1769 if (r)
1770 Py_DECREF(r);
1771 else
1772 PyErr_Clear();
1773 }
1774 f = PySys_GetObject("stdout");
1775 if (f != NULL) {
1776 r = PyObject_CallMethod(f, "flush", "");
1777 if (r)
1778 Py_DECREF(r);
1779 else
1780 PyErr_Clear();
1781 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001784}
1785
Guido van Rossum82598051997-03-05 00:20:32 +00001786static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 PyCodeObject *co;
1791 PyObject *v;
1792 co = PyAST_Compile(mod, filename, flags, arena);
1793 if (co == NULL)
1794 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001795 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 Py_DECREF(co);
1797 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001798}
1799
Guido van Rossum82598051997-03-05 00:20:32 +00001800static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001801run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 PyCodeObject *co;
1805 PyObject *v;
1806 long magic;
1807 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 magic = PyMarshal_ReadLongFromFile(fp);
1810 if (magic != PyImport_GetMagicNumber()) {
1811 PyErr_SetString(PyExc_RuntimeError,
1812 "Bad magic number in .pyc file");
1813 return NULL;
1814 }
1815 (void) PyMarshal_ReadLongFromFile(fp);
1816 v = PyMarshal_ReadLastObjectFromFile(fp);
1817 fclose(fp);
1818 if (v == NULL || !PyCode_Check(v)) {
1819 Py_XDECREF(v);
1820 PyErr_SetString(PyExc_RuntimeError,
1821 "Bad code object in .pyc file");
1822 return NULL;
1823 }
1824 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001825 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 if (v && flags)
1827 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1828 Py_DECREF(co);
1829 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001830}
1831
Guido van Rossum82598051997-03-05 00:20:32 +00001832PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001833Py_CompileStringExFlags(const char *str, const char *filename, int start,
1834 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 PyCodeObject *co;
1837 mod_ty mod;
1838 PyArena *arena = PyArena_New();
1839 if (arena == NULL)
1840 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1843 if (mod == NULL) {
1844 PyArena_Free(arena);
1845 return NULL;
1846 }
1847 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1848 PyObject *result = PyAST_mod2obj(mod);
1849 PyArena_Free(arena);
1850 return result;
1851 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001852 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 PyArena_Free(arena);
1854 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001855}
1856
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001857/* For use in Py_LIMITED_API */
1858#undef Py_CompileString
1859PyObject *
1860PyCompileString(const char *str, const char *filename, int start)
1861{
1862 return Py_CompileStringFlags(str, filename, start, NULL);
1863}
1864
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001865struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001866Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 struct symtable *st;
1869 mod_ty mod;
1870 PyCompilerFlags flags;
1871 PyArena *arena = PyArena_New();
1872 if (arena == NULL)
1873 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 flags.cf_flags = 0;
1876 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1877 if (mod == NULL) {
1878 PyArena_Free(arena);
1879 return NULL;
1880 }
1881 st = PySymtable_Build(mod, filename, 0);
1882 PyArena_Free(arena);
1883 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001884}
1885
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886/* Preferred access to parser is through AST. */
1887mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001888PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 mod_ty mod;
1892 PyCompilerFlags localflags;
1893 perrdetail err;
1894 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1897 &_PyParser_Grammar, start, &err,
1898 &iflags);
1899 if (flags == NULL) {
1900 localflags.cf_flags = 0;
1901 flags = &localflags;
1902 }
1903 if (n) {
1904 flags->cf_flags |= iflags & PyCF_MASK;
1905 mod = PyAST_FromNode(n, flags, filename, arena);
1906 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 }
1908 else {
1909 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001910 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001912 err_free(&err);
1913 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914}
1915
1916mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001917PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 int start, char *ps1,
1919 char *ps2, PyCompilerFlags *flags, int *errcode,
1920 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 mod_ty mod;
1923 PyCompilerFlags localflags;
1924 perrdetail err;
1925 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1928 &_PyParser_Grammar,
1929 start, ps1, ps2, &err, &iflags);
1930 if (flags == NULL) {
1931 localflags.cf_flags = 0;
1932 flags = &localflags;
1933 }
1934 if (n) {
1935 flags->cf_flags |= iflags & PyCF_MASK;
1936 mod = PyAST_FromNode(n, flags, filename, arena);
1937 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 }
1939 else {
1940 err_input(&err);
1941 if (errcode)
1942 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02001943 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001945 err_free(&err);
1946 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001947}
1948
Guido van Rossuma110aa61994-08-29 12:50:44 +00001949/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001950
Guido van Rossuma110aa61994-08-29 12:50:44 +00001951node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001952PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 perrdetail err;
1955 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1956 &_PyParser_Grammar,
1957 start, NULL, NULL, &err, flags);
1958 if (n == NULL)
1959 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001960 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001963}
1964
Guido van Rossuma110aa61994-08-29 12:50:44 +00001965/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001966
Guido van Rossuma110aa61994-08-29 12:50:44 +00001967node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001968PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 perrdetail err;
1971 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1972 start, &err, flags);
1973 if (n == NULL)
1974 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001975 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001977}
1978
1979node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001980PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 perrdetail err;
1984 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1985 &_PyParser_Grammar, start, &err, flags);
1986 if (n == NULL)
1987 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001988 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001990}
1991
1992node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001993PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001996}
1997
Guido van Rossum66ebd912003-04-17 16:02:26 +00001998/* May want to move a more generalized form of this to parsetok.c or
1999 even parser modules. */
2000
2001void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002002PyParser_ClearError(perrdetail *err)
2003{
2004 err_free(err);
2005}
2006
2007void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002008PyParser_SetError(perrdetail *err)
2009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002011}
2012
Victor Stinner7f2fee32011-04-05 00:39:01 +02002013static void
2014err_free(perrdetail *err)
2015{
2016 Py_CLEAR(err->filename);
2017}
2018
Guido van Rossuma110aa61994-08-29 12:50:44 +00002019/* Set the error appropriate to the given input error code (see errcode.h) */
2020
2021static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002022err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 PyObject *v, *w, *errtype, *errtext;
2025 PyObject *msg_obj = NULL;
2026 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 errtype = PyExc_SyntaxError;
2029 switch (err->error) {
2030 case E_ERROR:
2031 return;
2032 case E_SYNTAX:
2033 errtype = PyExc_IndentationError;
2034 if (err->expected == INDENT)
2035 msg = "expected an indented block";
2036 else if (err->token == INDENT)
2037 msg = "unexpected indent";
2038 else if (err->token == DEDENT)
2039 msg = "unexpected unindent";
2040 else {
2041 errtype = PyExc_SyntaxError;
2042 msg = "invalid syntax";
2043 }
2044 break;
2045 case E_TOKEN:
2046 msg = "invalid token";
2047 break;
2048 case E_EOFS:
2049 msg = "EOF while scanning triple-quoted string literal";
2050 break;
2051 case E_EOLS:
2052 msg = "EOL while scanning string literal";
2053 break;
2054 case E_INTR:
2055 if (!PyErr_Occurred())
2056 PyErr_SetNone(PyExc_KeyboardInterrupt);
2057 goto cleanup;
2058 case E_NOMEM:
2059 PyErr_NoMemory();
2060 goto cleanup;
2061 case E_EOF:
2062 msg = "unexpected EOF while parsing";
2063 break;
2064 case E_TABSPACE:
2065 errtype = PyExc_TabError;
2066 msg = "inconsistent use of tabs and spaces in indentation";
2067 break;
2068 case E_OVERFLOW:
2069 msg = "expression too long";
2070 break;
2071 case E_DEDENT:
2072 errtype = PyExc_IndentationError;
2073 msg = "unindent does not match any outer indentation level";
2074 break;
2075 case E_TOODEEP:
2076 errtype = PyExc_IndentationError;
2077 msg = "too many levels of indentation";
2078 break;
2079 case E_DECODE: {
2080 PyObject *type, *value, *tb;
2081 PyErr_Fetch(&type, &value, &tb);
2082 msg = "unknown decode error";
2083 if (value != NULL)
2084 msg_obj = PyObject_Str(value);
2085 Py_XDECREF(type);
2086 Py_XDECREF(value);
2087 Py_XDECREF(tb);
2088 break;
2089 }
2090 case E_LINECONT:
2091 msg = "unexpected character after line continuation character";
2092 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 case E_IDENTIFIER:
2095 msg = "invalid character in identifier";
2096 break;
2097 default:
2098 fprintf(stderr, "error=%d\n", err->error);
2099 msg = "unknown parsing error";
2100 break;
2101 }
2102 /* err->text may not be UTF-8 in case of decoding errors.
2103 Explicitly convert to an object. */
2104 if (!err->text) {
2105 errtext = Py_None;
2106 Py_INCREF(Py_None);
2107 } else {
2108 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2109 "replace");
2110 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002111 v = Py_BuildValue("(OiiN)", err->filename,
2112 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (v != NULL) {
2114 if (msg_obj)
2115 w = Py_BuildValue("(OO)", msg_obj, v);
2116 else
2117 w = Py_BuildValue("(sO)", msg, v);
2118 } else
2119 w = NULL;
2120 Py_XDECREF(v);
2121 PyErr_SetObject(errtype, w);
2122 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002123cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 Py_XDECREF(msg_obj);
2125 if (err->text != NULL) {
2126 PyObject_FREE(err->text);
2127 err->text = NULL;
2128 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002129}
2130
2131/* Print fatal error message and abort */
2132
2133void
Tim Peters7c321a82002-07-09 02:57:01 +00002134Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002135{
Victor Stinner024e37a2011-03-31 01:31:06 +02002136 const int fd = fileno(stderr);
2137 PyThreadState *tstate;
2138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 fprintf(stderr, "Fatal Python error: %s\n", msg);
2140 fflush(stderr); /* it helps in Windows debug build */
2141 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002142 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002144 else {
2145 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2146 if (tstate != NULL) {
2147 fputc('\n', stderr);
2148 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002149 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002150 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002151 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002152 }
2153
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002154#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 {
2156 size_t len = strlen(msg);
2157 WCHAR* buffer;
2158 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* Convert the message to wchar_t. This uses a simple one-to-one
2161 conversion, assuming that the this error message actually uses ASCII
2162 only. If this ceases to be true, we will have to convert. */
2163 buffer = alloca( (len+1) * (sizeof *buffer));
2164 for( i=0; i<=len; ++i)
2165 buffer[i] = msg[i];
2166 OutputDebugStringW(L"Fatal Python error: ");
2167 OutputDebugStringW(buffer);
2168 OutputDebugStringW(L"\n");
2169 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002170#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002172#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002173#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002175}
2176
2177/* Clean up and exit */
2178
Guido van Rossuma110aa61994-08-29 12:50:44 +00002179#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002180#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002181#endif
2182
Collin Winter670e6922007-03-21 02:57:17 +00002183static void (*pyexitfunc)(void) = NULL;
2184/* For the atexit module. */
2185void _Py_PyAtExit(void (*func)(void))
2186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002188}
2189
2190static void
2191call_py_exitfuncs(void)
2192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (pyexitfunc == NULL)
2194 return;
Collin Winter670e6922007-03-21 02:57:17 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 (*pyexitfunc)();
2197 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002198}
2199
Antoine Pitrou011bd622009-10-20 21:52:47 +00002200/* Wait until threading._shutdown completes, provided
2201 the threading module was imported in the first place.
2202 The shutdown routine will wait until all non-daemon
2203 "threading" threads have completed. */
2204static void
2205wait_for_thread_shutdown(void)
2206{
2207#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 PyObject *result;
2209 PyThreadState *tstate = PyThreadState_GET();
2210 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2211 "threading");
2212 if (threading == NULL) {
2213 /* threading not imported */
2214 PyErr_Clear();
2215 return;
2216 }
2217 result = PyObject_CallMethod(threading, "_shutdown", "");
2218 if (result == NULL) {
2219 PyErr_WriteUnraisable(threading);
2220 }
2221 else {
2222 Py_DECREF(result);
2223 }
2224 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002225#endif
2226}
2227
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002228#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002229static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002230static int nexitfuncs = 0;
2231
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002232int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 if (nexitfuncs >= NEXITFUNCS)
2235 return -1;
2236 exitfuncs[nexitfuncs++] = func;
2237 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002238}
2239
Guido van Rossumcc283f51997-08-05 02:22:03 +00002240static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002241call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 while (nexitfuncs > 0)
2244 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 fflush(stdout);
2247 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002248}
2249
2250void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002251Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002256}
2257
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002258static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002259initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002260{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002261#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002263#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002264#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002266#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002267#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002269#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002271}
2272
Guido van Rossum7433b121997-02-14 19:45:36 +00002273
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002274/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2275 *
2276 * All of the code in this function must only use async-signal-safe functions,
2277 * listed at `man 7 signal` or
2278 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2279 */
2280void
2281_Py_RestoreSignals(void)
2282{
2283#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002285#endif
2286#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002288#endif
2289#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002291#endif
2292}
2293
2294
Guido van Rossum7433b121997-02-14 19:45:36 +00002295/*
2296 * The file descriptor fd is considered ``interactive'' if either
2297 * a) isatty(fd) is TRUE, or
2298 * b) the -i flag was given, and the filename associated with
2299 * the descriptor is NULL or "<stdin>" or "???".
2300 */
2301int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002302Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 if (isatty((int)fileno(fp)))
2305 return 1;
2306 if (!Py_InteractiveFlag)
2307 return 0;
2308 return (filename == NULL) ||
2309 (strcmp(filename, "<stdin>") == 0) ||
2310 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002311}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002312
2313
Tim Petersd08e3822003-04-17 15:24:21 +00002314#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002315#if defined(WIN32) && defined(_MSC_VER)
2316
2317/* Stack checking for Microsoft C */
2318
2319#include <malloc.h>
2320#include <excpt.h>
2321
Fred Drakee8de31c2000-08-31 05:38:39 +00002322/*
2323 * Return non-zero when we run out of memory on the stack; zero otherwise.
2324 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002325int
Fred Drake399739f2000-08-31 05:52:44 +00002326PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 __try {
2329 /* alloca throws a stack overflow exception if there's
2330 not enough space left on the stack */
2331 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2332 return 0;
2333 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2334 EXCEPTION_EXECUTE_HANDLER :
2335 EXCEPTION_CONTINUE_SEARCH) {
2336 int errcode = _resetstkoflw();
2337 if (errcode == 0)
2338 {
2339 Py_FatalError("Could not reset the stack!");
2340 }
2341 }
2342 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002343}
2344
2345#endif /* WIN32 && _MSC_VER */
2346
2347/* Alternate implementations can be added here... */
2348
2349#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002350
2351
2352/* Wrappers around sigaction() or signal(). */
2353
2354PyOS_sighandler_t
2355PyOS_getsig(int sig)
2356{
2357#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 struct sigaction context;
2359 if (sigaction(sig, NULL, &context) == -1)
2360 return SIG_ERR;
2361 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002362#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002364/* Special signal handling for the secure CRT in Visual Studio 2005 */
2365#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 switch (sig) {
2367 /* Only these signals are valid */
2368 case SIGINT:
2369 case SIGILL:
2370 case SIGFPE:
2371 case SIGSEGV:
2372 case SIGTERM:
2373 case SIGBREAK:
2374 case SIGABRT:
2375 break;
2376 /* Don't call signal() with other values or it will assert */
2377 default:
2378 return SIG_ERR;
2379 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002380#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 handler = signal(sig, SIG_IGN);
2382 if (handler != SIG_ERR)
2383 signal(sig, handler);
2384 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002385#endif
2386}
2387
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002388/*
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 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002393PyOS_sighandler_t
2394PyOS_setsig(int sig, PyOS_sighandler_t handler)
2395{
2396#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* Some code in Modules/signalmodule.c depends on sigaction() being
2398 * used here if HAVE_SIGACTION is defined. Fix that if this code
2399 * changes to invalidate that assumption.
2400 */
2401 struct sigaction context, ocontext;
2402 context.sa_handler = handler;
2403 sigemptyset(&context.sa_mask);
2404 context.sa_flags = 0;
2405 if (sigaction(sig, &context, &ocontext) == -1)
2406 return SIG_ERR;
2407 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002408#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 PyOS_sighandler_t oldhandler;
2410 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002411#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002413#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002415#endif
2416}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002417
2418/* Deprecated C API functions still provided for binary compatiblity */
2419
2420#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002421PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002422PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002425}
2426
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002427#undef PyParser_SimpleParseString
2428PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002429PyParser_SimpleParseString(const char *str, int start)
2430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002432}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002433
2434#undef PyRun_AnyFile
2435PyAPI_FUNC(int)
2436PyRun_AnyFile(FILE *fp, const char *name)
2437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002439}
2440
2441#undef PyRun_AnyFileEx
2442PyAPI_FUNC(int)
2443PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002446}
2447
2448#undef PyRun_AnyFileFlags
2449PyAPI_FUNC(int)
2450PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002453}
2454
2455#undef PyRun_File
2456PyAPI_FUNC(PyObject *)
2457PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002460}
2461
2462#undef PyRun_FileEx
2463PyAPI_FUNC(PyObject *)
2464PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002467}
2468
2469#undef PyRun_FileFlags
2470PyAPI_FUNC(PyObject *)
2471PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002475}
2476
2477#undef PyRun_SimpleFile
2478PyAPI_FUNC(int)
2479PyRun_SimpleFile(FILE *f, const char *p)
2480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002482}
2483
2484#undef PyRun_SimpleFileEx
2485PyAPI_FUNC(int)
2486PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002489}
2490
2491
2492#undef PyRun_String
2493PyAPI_FUNC(PyObject *)
2494PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002497}
2498
2499#undef PyRun_SimpleString
2500PyAPI_FUNC(int)
2501PyRun_SimpleString(const char *s)
2502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002504}
2505
2506#undef Py_CompileString
2507PyAPI_FUNC(PyObject *)
2508Py_CompileString(const char *str, const char *p, int s)
2509{
Georg Brandl8334fd92010-12-04 10:26:46 +00002510 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2511}
2512
2513#undef Py_CompileStringFlags
2514PyAPI_FUNC(PyObject *)
2515Py_CompileStringFlags(const char *str, const char *p, int s,
2516 PyCompilerFlags *flags)
2517{
2518 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002519}
2520
2521#undef PyRun_InteractiveOne
2522PyAPI_FUNC(int)
2523PyRun_InteractiveOne(FILE *f, const char *p)
2524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002526}
2527
2528#undef PyRun_InteractiveLoop
2529PyAPI_FUNC(int)
2530PyRun_InteractiveLoop(FILE *f, const char *p)
2531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002533}
2534
2535#ifdef __cplusplus
2536}
2537#endif