blob: f787a4f8b372b27d66a2afdb319ee6ce85680e2e [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 Stinnerb744ba12010-05-15 12:27:16 +000056static void initfsencoding(void);
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 *);
65static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000066static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000067static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000068static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000069extern void _PyUnicode_Init(void);
70extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000071extern int _PyLong_Init(void);
72extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020073extern int _PyFaulthandler_Init(void);
74extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000075
Mark Hammond8d98d2c2003-04-19 15:41:53 +000076#ifdef WITH_THREAD
77extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
78extern void _PyGILState_Fini(void);
79#endif /* WITH_THREAD */
80
Guido van Rossum82598051997-03-05 00:20:32 +000081int Py_DebugFlag; /* Needed by parser.c */
82int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000083int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000084int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000085int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000086int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000087int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000088int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000089int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000090int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000091int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000092int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000093int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000094
Christian Heimes33fe8092008-04-13 13:53:33 +000095/* PyModule_GetWarningsModule is no longer necessary as of 2.6
96since _warnings is builtin. This API should not be used. */
97PyObject *
98PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000101}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000102
Guido van Rossum25ce5661997-08-02 03:10:38 +0000103static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000104
Thomas Wouters7e474022000-07-16 12:04:32 +0000105/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106
107int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000108Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111}
112
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113/* Global initializations. Can be undone by Py_Finalize(). Don't
114 call this twice without an intervening Py_Finalize() call. When
115 initializations fail, a fatal error is issued and the function does
116 not return. On return, the first thread and interpreter state have
117 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119 Locking: you must hold the interpreter lock while calling this.
120 (If the lock has not yet been initialized, that's equivalent to
121 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000125static int
126add_flag(int flag, const char *envs)
127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 int env = atoi(envs);
129 if (flag < env)
130 flag = env;
131 if (flag < 1)
132 flag = 1;
133 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000134}
135
Christian Heimes5833a2f2008-10-30 21:40:04 +0000136static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000137get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000138{
Victor Stinner94908bb2010-08-18 21:23:25 +0000139 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000140 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000141
Victor Stinner94908bb2010-08-18 21:23:25 +0000142 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (!codec)
144 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 name = PyObject_GetAttrString(codec, "name");
147 Py_CLEAR(codec);
148 if (!name)
149 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000150
Victor Stinner94908bb2010-08-18 21:23:25 +0000151 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100152 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000153 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000154 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000156 if (name_str == NULL) {
157 PyErr_NoMemory();
158 return NULL;
159 }
160 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000161
162error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000164 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000166}
Victor Stinner94908bb2010-08-18 21:23:25 +0000167
168#if defined(HAVE_LANGINFO_H) && defined(CODESET)
169static char*
170get_codeset(void)
171{
172 char* codeset = nl_langinfo(CODESET);
173 if (!codeset || codeset[0] == '\0') {
174 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
175 return NULL;
176 }
177 return get_codec_name(codeset);
178}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000179#endif
180
Guido van Rossuma027efa1997-05-05 20:56:21 +0000181void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000182Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 PyInterpreterState *interp;
185 PyThreadState *tstate;
186 PyObject *bimod, *sysmod, *pstderr;
187 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (initialized)
191 return;
192 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000193
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000194#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 /* Set up the LC_CTYPE locale, so we can obtain
196 the locale's charset without having to switch
197 locales. */
198 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000199#endif
200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
202 Py_DebugFlag = add_flag(Py_DebugFlag, p);
203 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
204 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
205 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
206 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
207 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
208 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 interp = PyInterpreterState_New();
211 if (interp == NULL)
212 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 tstate = PyThreadState_New(interp);
215 if (tstate == NULL)
216 Py_FatalError("Py_Initialize: can't make first thread");
217 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000218
Victor Stinner6961bd62010-08-17 22:26:51 +0000219#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000220 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
221 destroying the GIL might fail when it is being referenced from
222 another running thread (see issue #9901).
223 Instead we destroy the previously created GIL here, which ensures
224 that we can call Py_Initialize / Py_Finalize multiple times. */
225 _PyEval_FiniThreads();
226
227 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000228 _PyGILState_Init(interp, tstate);
229#endif /* WITH_THREAD */
230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (!_PyFrame_Init())
234 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (!_PyLong_Init())
237 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (!PyByteArray_Init())
240 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 interp->modules = PyDict_New();
245 if (interp->modules == NULL)
246 Py_FatalError("Py_Initialize: can't make modules dictionary");
247 interp->modules_reloading = PyDict_New();
248 if (interp->modules_reloading == NULL)
249 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 /* Init Unicode implementation; relies on the codec registry */
252 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 bimod = _PyBuiltin_Init();
255 if (bimod == NULL)
256 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000257 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 interp->builtins = PyModule_GetDict(bimod);
259 if (interp->builtins == NULL)
260 Py_FatalError("Py_Initialize: can't initialize builtins dict");
261 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 /* initialize builtin exceptions */
264 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 sysmod = _PySys_Init();
267 if (sysmod == NULL)
268 Py_FatalError("Py_Initialize: can't initialize sys");
269 interp->sysdict = PyModule_GetDict(sysmod);
270 if (interp->sysdict == NULL)
271 Py_FatalError("Py_Initialize: can't initialize sys dict");
272 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000273 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PySys_SetPath(Py_GetPath());
275 PyDict_SetItemString(interp->sysdict, "modules",
276 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 /* Set up a preliminary stderr printer until we have enough
279 infrastructure for the io module in place. */
280 pstderr = PyFile_NewStdPrinter(fileno(stderr));
281 if (pstderr == NULL)
282 Py_FatalError("Py_Initialize: can't set preliminary stderr");
283 PySys_SetObject("stderr", pstderr);
284 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000285 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000290
Victor Stinner024e37a2011-03-31 01:31:06 +0200291 /* initialize the faulthandler module */
292 if (_PyFaulthandler_Init())
293 Py_FatalError("Py_Initialize: can't initialize faulthandler");
294
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000295 /* Initialize _warnings. */
296 _PyWarnings_Init();
297
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000298 _PyTime_Init();
299
Victor Stinnerb744ba12010-05-15 12:27:16 +0000300 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 if (install_sigs)
303 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 initmain(); /* Module __main__ */
306 if (initstdio() < 0)
307 Py_FatalError(
308 "Py_Initialize: can't initialize sys standard streams");
309
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000310 /* Initialize warnings. */
311 if (PySys_HasWarnOptions()) {
312 PyObject *warnings_module = PyImport_ImportModule("warnings");
313 if (warnings_module == NULL) {
314 fprintf(stderr, "'import warnings' failed; traceback:\n");
315 PyErr_Print();
316 }
317 Py_XDECREF(warnings_module);
318 }
319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (!Py_NoSiteFlag)
321 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000322}
323
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000324void
325Py_Initialize(void)
326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000328}
329
330
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000331#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000332extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000333#endif
334
Guido van Rossume8432ac2007-07-09 15:04:50 +0000335/* Flush stdout and stderr */
336
Neal Norwitz2bad9702007-08-27 06:19:22 +0000337static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000338flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 PyObject *fout = PySys_GetObject("stdout");
341 PyObject *ferr = PySys_GetObject("stderr");
342 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 if (fout != NULL && fout != Py_None) {
345 tmp = PyObject_CallMethod(fout, "flush", "");
346 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000347 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 else
349 Py_DECREF(tmp);
350 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000351
Victor Stinner9467b212010-05-14 00:59:09 +0000352 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 tmp = PyObject_CallMethod(ferr, "flush", "");
354 if (tmp == NULL)
355 PyErr_Clear();
356 else
357 Py_DECREF(tmp);
358 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000359}
360
Guido van Rossum25ce5661997-08-02 03:10:38 +0000361/* Undo the effect of Py_Initialize().
362
363 Beware: if multiple interpreter and/or thread states exist, these
364 are not wiped out; only the current thread and interpreter state
365 are deleted. But since everything else is deleted, those other
366 interpreter and thread states should no longer be used.
367
368 (XXX We should do better, e.g. wipe out all interpreters and
369 threads.)
370
371 Locking: as above.
372
373*/
374
375void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000376Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 PyInterpreterState *interp;
379 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (!initialized)
382 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 /* The interpreter is still entirely intact at this point, and the
387 * exit funcs may be relying on that. In particular, if some thread
388 * or exit func is still waiting to do an import, the import machinery
389 * expects Py_IsInitialized() to return true. So don't say the
390 * interpreter is uninitialized until after the exit funcs have run.
391 * Note that Threading.py uses an exit func to do a join on all the
392 * threads created thru it, so this also protects pending imports in
393 * the threads created via Threading.
394 */
395 call_py_exitfuncs();
396 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 /* Flush stdout+stderr */
399 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 /* Get current thread state and interpreter pointer */
402 tstate = PyThreadState_GET();
403 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 /* Disable signal handling */
406 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 /* Clear type lookup cache */
409 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 /* Collect garbage. This may call finalizers; it's nice to call these
412 * before all modules are destroyed.
413 * XXX If a __del__ or weakref callback is triggered here, and tries to
414 * XXX import a module, bad things can happen, because Python no
415 * XXX longer believes it's initialized.
416 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
417 * XXX is easy to provoke that way. I've also seen, e.g.,
418 * XXX Exception exceptions.ImportError: 'No module named sha'
419 * XXX in <function callback at 0x008F5718> ignored
420 * XXX but I'm unclear on exactly how that one happens. In any case,
421 * XXX I haven't seen a real-life report of either of these.
422 */
423 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000424#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 /* With COUNT_ALLOCS, it helps to run GC multiple times:
426 each collection might release some types from the type
427 list, so they become garbage. */
428 while (PyGC_Collect() > 0)
429 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000430#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000431 /* We run this while most interpreter state is still alive, so that
432 debug information can be printed out */
433 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* Destroy all modules */
436 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 /* Flush stdout+stderr (again, in case more was printed) */
439 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 /* Collect final garbage. This disposes of cycles created by
442 * new-style class definitions, for example.
443 * XXX This is disabled because it caused too many problems. If
444 * XXX a __del__ or weakref callback triggers here, Python code has
445 * XXX a hard time running, because even the sys module has been
446 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
447 * XXX One symptom is a sequence of information-free messages
448 * XXX coming from threads (if a __del__ or callback is invoked,
449 * XXX other threads can execute too, and any exception they encounter
450 * XXX triggers a comedy of errors as subsystem after subsystem
451 * XXX fails to find what it *expects* to find in sys to help report
452 * XXX the exception and consequent unexpected failures). I've also
453 * XXX seen segfaults then, after adding print statements to the
454 * XXX Python code getting called.
455 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000456#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000458#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
461 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000462
Victor Stinner024e37a2011-03-31 01:31:06 +0200463 /* unload faulthandler module */
464 _PyFaulthandler_Fini();
465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000467#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000469#endif
470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000472
Tim Peters9cf25ce2003-04-17 15:21:01 +0000473#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* Display all objects still alive -- this can invoke arbitrary
475 * __repr__ overrides, so requires a mostly-intact interpreter.
476 * Alas, a lot of stuff may still be alive now that will be cleaned
477 * up later.
478 */
479 if (Py_GETENV("PYTHONDUMPREFS"))
480 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000481#endif /* Py_TRACE_REFS */
482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 /* Clear interpreter state */
484 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 /* Now we decref the exception classes. After this point nothing
487 can raise an exception. That's okay, because each Fini() method
488 below has been checked to make sure no exceptions are ever
489 raised.
490 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000495#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000497#endif /* WITH_THREAD */
498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 /* Delete current thread */
500 PyThreadState_Swap(NULL);
501 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* Sundry finalizers */
504 PyMethod_Fini();
505 PyFrame_Fini();
506 PyCFunction_Fini();
507 PyTuple_Fini();
508 PyList_Fini();
509 PySet_Fini();
510 PyBytes_Fini();
511 PyByteArray_Fini();
512 PyLong_Fini();
513 PyFloat_Fini();
514 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* Cleanup Unicode implementation */
517 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000520 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 free((char*)Py_FileSystemDefaultEncoding);
522 Py_FileSystemDefaultEncoding = NULL;
523 }
Christian Heimesc8967002007-11-30 10:18:26 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* XXX Still allocated:
526 - various static ad-hoc pointers to interned strings
527 - int and float free list blocks
528 - whatever various modules and libraries allocate
529 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000532
Tim Peters269b2a62003-04-17 19:52:29 +0000533#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 /* Display addresses (& refcnts) of all objects still alive.
535 * An address can be used to find the repr of the object, printed
536 * above by _Py_PrintReferences.
537 */
538 if (Py_GETENV("PYTHONDUMPREFS"))
539 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000540#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000541#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (Py_GETENV("PYTHONMALLOCSTATS"))
543 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000544#endif
545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000547}
548
549/* Create and initialize a new interpreter and thread, and return the
550 new thread. This requires that Py_Initialize() has been called
551 first.
552
553 Unsuccessful initialization yields a NULL pointer. Note that *no*
554 exception information is available even in this case -- the
555 exception information is held in the thread, and there is no
556 thread.
557
558 Locking: as above.
559
560*/
561
562PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000563Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 PyInterpreterState *interp;
566 PyThreadState *tstate, *save_tstate;
567 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 if (!initialized)
570 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 interp = PyInterpreterState_New();
573 if (interp == NULL)
574 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 tstate = PyThreadState_New(interp);
577 if (tstate == NULL) {
578 PyInterpreterState_Delete(interp);
579 return NULL;
580 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 interp->modules = PyDict_New();
587 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588
Victor Stinner49d3f252010-10-17 01:24:53 +0000589 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (bimod != NULL) {
591 interp->builtins = PyModule_GetDict(bimod);
592 if (interp->builtins == NULL)
593 goto handle_error;
594 Py_INCREF(interp->builtins);
595 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 /* initialize builtin exceptions */
598 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000599
Victor Stinner49d3f252010-10-17 01:24:53 +0000600 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (bimod != NULL && sysmod != NULL) {
602 PyObject *pstderr;
603 interp->sysdict = PyModule_GetDict(sysmod);
604 if (interp->sysdict == NULL)
605 goto handle_error;
606 Py_INCREF(interp->sysdict);
607 PySys_SetPath(Py_GetPath());
608 PyDict_SetItemString(interp->sysdict, "modules",
609 interp->modules);
610 /* Set up a preliminary stderr printer until we have enough
611 infrastructure for the io module in place. */
612 pstderr = PyFile_NewStdPrinter(fileno(stderr));
613 if (pstderr == NULL)
614 Py_FatalError("Py_Initialize: can't set preliminary stderr");
615 PySys_SetObject("stderr", pstderr);
616 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000617 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 _PyImportHooks_Init();
620 if (initstdio() < 0)
621 Py_FatalError(
622 "Py_Initialize: can't initialize sys standard streams");
623 initmain();
624 if (!Py_NoSiteFlag)
625 initsite();
626 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (!PyErr_Occurred())
629 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630
Thomas Wouters89f507f2006-12-13 04:49:30 +0000631handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 PyErr_Print();
635 PyThreadState_Clear(tstate);
636 PyThreadState_Swap(save_tstate);
637 PyThreadState_Delete(tstate);
638 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000641}
642
643/* Delete an interpreter and its last thread. This requires that the
644 given thread state is current, that the thread has no remaining
645 frames, and that it is its interpreter's only remaining thread.
646 It is a fatal error to violate these constraints.
647
648 (Py_Finalize() doesn't have these constraints -- it zaps
649 everything, regardless.)
650
651 Locking: as above.
652
653*/
654
655void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000656Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (tstate != PyThreadState_GET())
661 Py_FatalError("Py_EndInterpreter: thread is not current");
662 if (tstate->frame != NULL)
663 Py_FatalError("Py_EndInterpreter: thread still has a frame");
664 if (tstate != interp->tstate_head || tstate->next != NULL)
665 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyImport_Cleanup();
668 PyInterpreterState_Clear(interp);
669 PyThreadState_Swap(NULL);
670 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000671}
672
Martin v. Löwis790465f2008-04-05 20:41:37 +0000673static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000674
675void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000676Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (pn && *pn)
679 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000680}
681
Martin v. Löwis790465f2008-04-05 20:41:37 +0000682wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000683Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000686}
687
Martin v. Löwis790465f2008-04-05 20:41:37 +0000688static wchar_t *default_home = NULL;
689static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000690
691void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000692Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000695}
696
Martin v. Löwis790465f2008-04-05 20:41:37 +0000697wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000698Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 wchar_t *home = default_home;
701 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
702 char* chome = Py_GETENV("PYTHONHOME");
703 if (chome) {
704 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
705 if (r != (size_t)-1 && r <= PATH_MAX)
706 home = env_home;
707 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 }
710 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000711}
712
Guido van Rossum6135a871995-01-09 17:53:26 +0000713/* Create __main__ module */
714
715static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000716initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 PyObject *m, *d;
719 m = PyImport_AddModule("__main__");
720 if (m == NULL)
721 Py_FatalError("can't create __main__ module");
722 d = PyModule_GetDict(m);
723 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
724 PyObject *bimod = PyImport_ImportModule("builtins");
725 if (bimod == NULL ||
726 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
727 Py_FatalError("can't add __builtins__ to __main__");
728 Py_DECREF(bimod);
729 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000730}
731
Victor Stinnerb744ba12010-05-15 12:27:16 +0000732static void
733initfsencoding(void)
734{
735 PyObject *codec;
736#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000737 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000738
Victor Stinner7f84ab52010-06-11 00:36:33 +0000739 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000740 /* On Unix, set the file system encoding according to the
741 user's preference, if the CODESET names a well-known
742 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000743 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000744 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000745 if (codeset == NULL)
746 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000747
Victor Stinnere4743092010-10-19 00:05:51 +0000748 Py_FileSystemDefaultEncoding = codeset;
749 Py_HasFileSystemDefaultEncoding = 0;
750 return;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000751 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000752#endif
753
754 /* the encoding is mbcs, utf-8 or ascii */
755 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
756 if (!codec) {
757 /* Such error can only occurs in critical situations: no more
758 * memory, import a module of the standard library failed,
759 * etc. */
760 Py_FatalError("Py_Initialize: unable to load the file system codec");
761 } else {
762 Py_DECREF(codec);
763 }
764}
765
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000766/* Import the site module (not into __main__ though) */
767
768static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000769initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 PyObject *m;
772 m = PyImport_ImportModule("site");
773 if (m == NULL) {
774 PyErr_Print();
775 Py_Finalize();
776 exit(1);
777 }
778 else {
779 Py_DECREF(m);
780 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000781}
782
Antoine Pitrou05608432009-01-09 18:53:14 +0000783static PyObject*
784create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 int fd, int write_mode, char* name,
786 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
789 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000790 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 PyObject *line_buffering;
792 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 /* stdin is always opened in buffered mode, first because it shouldn't
795 make a difference in common use cases, second because TextIOWrapper
796 depends on the presence of a read1() method which only exists on
797 buffered streams.
798 */
799 if (Py_UnbufferedStdioFlag && write_mode)
800 buffering = 0;
801 else
802 buffering = -1;
803 if (write_mode)
804 mode = "wb";
805 else
806 mode = "rb";
807 buf = PyObject_CallMethod(io, "open", "isiOOOi",
808 fd, mode, buffering,
809 Py_None, Py_None, Py_None, 0);
810 if (buf == NULL)
811 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (buffering) {
814 raw = PyObject_GetAttrString(buf, "raw");
815 if (raw == NULL)
816 goto error;
817 }
818 else {
819 raw = buf;
820 Py_INCREF(raw);
821 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 text = PyUnicode_FromString(name);
824 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
825 goto error;
826 res = PyObject_CallMethod(raw, "isatty", "");
827 if (res == NULL)
828 goto error;
829 isatty = PyObject_IsTrue(res);
830 Py_DECREF(res);
831 if (isatty == -1)
832 goto error;
833 if (isatty || Py_UnbufferedStdioFlag)
834 line_buffering = Py_True;
835 else
836 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 Py_CLEAR(raw);
839 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000840
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000841 newline = "\n";
842#ifdef MS_WINDOWS
843 if (!write_mode) {
844 /* translate \r\n to \n for sys.stdin on Windows */
845 newline = NULL;
846 }
847#endif
848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
850 buf, encoding, errors,
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000851 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 Py_CLEAR(buf);
853 if (stream == NULL)
854 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 if (write_mode)
857 mode = "w";
858 else
859 mode = "r";
860 text = PyUnicode_FromString(mode);
861 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
862 goto error;
863 Py_CLEAR(text);
864 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000865
866error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 Py_XDECREF(buf);
868 Py_XDECREF(stream);
869 Py_XDECREF(text);
870 Py_XDECREF(raw);
871 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000872}
873
Georg Brandl1a3284e2007-12-02 09:40:06 +0000874/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000875static int
876initstdio(void)
877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 PyObject *iomod = NULL, *wrapper;
879 PyObject *bimod = NULL;
880 PyObject *m;
881 PyObject *std = NULL;
882 int status = 0, fd;
883 PyObject * encoding_attr;
884 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 /* Hack to avoid a nasty recursion issue when Python is invoked
887 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
888 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
889 goto error;
890 }
891 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
894 goto error;
895 }
896 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 if (!(bimod = PyImport_ImportModule("builtins"))) {
899 goto error;
900 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 if (!(iomod = PyImport_ImportModule("io"))) {
903 goto error;
904 }
905 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
906 goto error;
907 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 /* Set builtins.open */
910 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000911 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 goto error;
913 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000914 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 encoding = Py_GETENV("PYTHONIOENCODING");
917 errors = NULL;
918 if (encoding) {
919 encoding = strdup(encoding);
920 errors = strchr(encoding, ':');
921 if (errors) {
922 *errors = '\0';
923 errors++;
924 }
925 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 /* Set sys.stdin */
928 fd = fileno(stdin);
929 /* Under some conditions stdin, stdout and stderr may not be connected
930 * and fileno() may point to an invalid file descriptor. For example
931 * GUI apps don't have valid standard streams by default.
932 */
933 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000934#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 std = Py_None;
936 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000937#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000939#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 }
941 else {
942 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
943 if (std == NULL)
944 goto error;
945 } /* if (fd < 0) */
946 PySys_SetObject("__stdin__", std);
947 PySys_SetObject("stdin", std);
948 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* Set sys.stdout */
951 fd = fileno(stdout);
952 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000953#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 std = Py_None;
955 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000956#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000958#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 }
960 else {
961 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
962 if (std == NULL)
963 goto error;
964 } /* if (fd < 0) */
965 PySys_SetObject("__stdout__", std);
966 PySys_SetObject("stdout", std);
967 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000968
Guido van Rossum98297ee2007-11-06 21:34:58 +0000969#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* Set sys.stderr, replaces the preliminary stderr */
971 fd = fileno(stderr);
972 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000973#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 std = Py_None;
975 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000976#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000978#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 }
980 else {
981 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
982 if (std == NULL)
983 goto error;
984 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 /* Same as hack above, pre-import stderr's codec to avoid recursion
987 when import.c tries to write to stderr in verbose mode. */
988 encoding_attr = PyObject_GetAttrString(std, "encoding");
989 if (encoding_attr != NULL) {
990 const char * encoding;
991 encoding = _PyUnicode_AsString(encoding_attr);
992 if (encoding != NULL) {
993 _PyCodec_Lookup(encoding);
994 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000995 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 }
997 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PySys_SetObject("__stderr__", std);
1000 PySys_SetObject("stderr", std);
1001 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001002#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001005 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 status = -1;
1007 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (encoding)
1010 free(encoding);
1011 Py_XDECREF(bimod);
1012 Py_XDECREF(iomod);
1013 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001014}
1015
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001016/* Parse input from a file and execute it */
1017
1018int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001019PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (filename == NULL)
1023 filename = "???";
1024 if (Py_FdIsInteractive(fp, filename)) {
1025 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1026 if (closeit)
1027 fclose(fp);
1028 return err;
1029 }
1030 else
1031 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001032}
1033
1034int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001035PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 PyObject *v;
1038 int ret;
1039 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 if (flags == NULL) {
1042 flags = &local_flags;
1043 local_flags.cf_flags = 0;
1044 }
1045 v = PySys_GetObject("ps1");
1046 if (v == NULL) {
1047 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1048 Py_XDECREF(v);
1049 }
1050 v = PySys_GetObject("ps2");
1051 if (v == NULL) {
1052 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1053 Py_XDECREF(v);
1054 }
1055 for (;;) {
1056 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1057 PRINT_TOTAL_REFS();
1058 if (ret == E_EOF)
1059 return 0;
1060 /*
1061 if (ret == E_NOMEM)
1062 return -1;
1063 */
1064 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001065}
1066
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001067/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001068static int PARSER_FLAGS(PyCompilerFlags *flags)
1069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 int parser_flags = 0;
1071 if (!flags)
1072 return 0;
1073 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1074 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1075 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1076 parser_flags |= PyPARSE_IGNORE_COOKIE;
1077 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1078 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1079 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001080}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001081
Thomas Wouters89f507f2006-12-13 04:49:30 +00001082#if 0
1083/* Keep an example of flags with future keyword support. */
1084#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1086 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1087 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1088 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001089#endif
1090
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001091int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001092PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyObject *m, *d, *v, *w, *oenc = NULL;
1095 mod_ty mod;
1096 PyArena *arena;
1097 char *ps1 = "", *ps2 = "", *enc = NULL;
1098 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 if (fp == stdin) {
1101 /* Fetch encoding from sys.stdin */
1102 v = PySys_GetObject("stdin");
1103 if (v == NULL || v == Py_None)
1104 return -1;
1105 oenc = PyObject_GetAttrString(v, "encoding");
1106 if (!oenc)
1107 return -1;
1108 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001109 if (enc == NULL)
1110 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 }
1112 v = PySys_GetObject("ps1");
1113 if (v != NULL) {
1114 v = PyObject_Str(v);
1115 if (v == NULL)
1116 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001117 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001119 if (ps1 == NULL) {
1120 PyErr_Clear();
1121 ps1 = "";
1122 }
1123 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 }
1125 w = PySys_GetObject("ps2");
1126 if (w != NULL) {
1127 w = PyObject_Str(w);
1128 if (w == NULL)
1129 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001130 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001132 if (ps2 == NULL) {
1133 PyErr_Clear();
1134 ps2 = "";
1135 }
1136 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 }
1138 arena = PyArena_New();
1139 if (arena == NULL) {
1140 Py_XDECREF(v);
1141 Py_XDECREF(w);
1142 Py_XDECREF(oenc);
1143 return -1;
1144 }
1145 mod = PyParser_ASTFromFile(fp, filename, enc,
1146 Py_single_input, ps1, ps2,
1147 flags, &errcode, arena);
1148 Py_XDECREF(v);
1149 Py_XDECREF(w);
1150 Py_XDECREF(oenc);
1151 if (mod == NULL) {
1152 PyArena_Free(arena);
1153 if (errcode == E_EOF) {
1154 PyErr_Clear();
1155 return E_EOF;
1156 }
1157 PyErr_Print();
1158 return -1;
1159 }
1160 m = PyImport_AddModule("__main__");
1161 if (m == NULL) {
1162 PyArena_Free(arena);
1163 return -1;
1164 }
1165 d = PyModule_GetDict(m);
1166 v = run_mod(mod, filename, d, d, flags, arena);
1167 PyArena_Free(arena);
1168 flush_io();
1169 if (v == NULL) {
1170 PyErr_Print();
1171 return -1;
1172 }
1173 Py_DECREF(v);
1174 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001175}
1176
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001177/* Check whether a file maybe a pyc file: Look at the extension,
1178 the file type, and, if we may close it, at the first few bytes. */
1179
1180static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001181maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1184 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 /* Only look into the file if we are allowed to close it, since
1187 it then should also be seekable. */
1188 if (closeit) {
1189 /* Read only two bytes of the magic. If the file was opened in
1190 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1191 be read as they are on disk. */
1192 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1193 unsigned char buf[2];
1194 /* Mess: In case of -x, the stream is NOT at its start now,
1195 and ungetc() was used to push back the first newline,
1196 which makes the current stream position formally undefined,
1197 and a x-platform nightmare.
1198 Unfortunately, we have no direct way to know whether -x
1199 was specified. So we use a terrible hack: if the current
1200 stream position is not 0, we assume -x was specified, and
1201 give up. Bug 132850 on SourceForge spells out the
1202 hopelessness of trying anything else (fseek and ftell
1203 don't work predictably x-platform for text-mode files).
1204 */
1205 int ispyc = 0;
1206 if (ftell(fp) == 0) {
1207 if (fread(buf, 1, 2, fp) == 2 &&
1208 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1209 ispyc = 1;
1210 rewind(fp);
1211 }
1212 return ispyc;
1213 }
1214 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001215}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001216
Guido van Rossum0df002c2000-08-27 19:21:52 +00001217int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001218PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 PyObject *m, *d, *v;
1222 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001223 int set_file_name = 0, ret;
1224 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 m = PyImport_AddModule("__main__");
1227 if (m == NULL)
1228 return -1;
1229 d = PyModule_GetDict(m);
1230 if (PyDict_GetItemString(d, "__file__") == NULL) {
1231 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001232 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (f == NULL)
1234 return -1;
1235 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1236 Py_DECREF(f);
1237 return -1;
1238 }
1239 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1240 return -1;
1241 set_file_name = 1;
1242 Py_DECREF(f);
1243 }
1244 len = strlen(filename);
1245 ext = filename + len - (len > 4 ? 4 : 0);
1246 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1247 /* Try to run a pyc file. First, re-open in binary */
1248 if (closeit)
1249 fclose(fp);
1250 if ((fp = fopen(filename, "rb")) == NULL) {
1251 fprintf(stderr, "python: Can't reopen .pyc file\n");
1252 ret = -1;
1253 goto done;
1254 }
1255 /* Turn on optimization if a .pyo file is given */
1256 if (strcmp(ext, ".pyo") == 0)
1257 Py_OptimizeFlag = 1;
1258 v = run_pyc_file(fp, filename, d, d, flags);
1259 } else {
1260 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1261 closeit, flags);
1262 }
1263 flush_io();
1264 if (v == NULL) {
1265 PyErr_Print();
1266 ret = -1;
1267 goto done;
1268 }
1269 Py_DECREF(v);
1270 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001271 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1273 PyErr_Clear();
1274 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001275}
1276
1277int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001278PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 PyObject *m, *d, *v;
1281 m = PyImport_AddModule("__main__");
1282 if (m == NULL)
1283 return -1;
1284 d = PyModule_GetDict(m);
1285 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1286 if (v == NULL) {
1287 PyErr_Print();
1288 return -1;
1289 }
1290 Py_DECREF(v);
1291 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001292}
1293
Barry Warsaw035574d1997-08-29 22:07:17 +00001294static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001295parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 long hold;
1299 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 /* old style errors */
1302 if (PyTuple_Check(err))
1303 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1304 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 if (! (v = PyObject_GetAttrString(err, "msg")))
1309 goto finally;
1310 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 if (!(v = PyObject_GetAttrString(err, "filename")))
1313 goto finally;
1314 if (v == Py_None)
1315 *filename = NULL;
1316 else if (! (*filename = _PyUnicode_AsString(v)))
1317 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 Py_DECREF(v);
1320 if (!(v = PyObject_GetAttrString(err, "lineno")))
1321 goto finally;
1322 hold = PyLong_AsLong(v);
1323 Py_DECREF(v);
1324 v = NULL;
1325 if (hold < 0 && PyErr_Occurred())
1326 goto finally;
1327 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 if (!(v = PyObject_GetAttrString(err, "offset")))
1330 goto finally;
1331 if (v == Py_None) {
1332 *offset = -1;
1333 Py_DECREF(v);
1334 v = NULL;
1335 } else {
1336 hold = PyLong_AsLong(v);
1337 Py_DECREF(v);
1338 v = NULL;
1339 if (hold < 0 && PyErr_Occurred())
1340 goto finally;
1341 *offset = (int)hold;
1342 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (!(v = PyObject_GetAttrString(err, "text")))
1345 goto finally;
1346 if (v == Py_None)
1347 *text = NULL;
1348 else if (!PyUnicode_Check(v) ||
1349 !(*text = _PyUnicode_AsString(v)))
1350 goto finally;
1351 Py_DECREF(v);
1352 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001353
1354finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 Py_XDECREF(v);
1356 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001357}
1358
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001359void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001360PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001363}
1364
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001365static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001366print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 char *nl;
1369 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001370 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1371 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 for (;;) {
1373 nl = strchr(text, '\n');
1374 if (nl == NULL || nl-text >= offset)
1375 break;
1376 offset -= (int)(nl+1-text);
1377 text = nl+1;
1378 }
1379 while (*text == ' ' || *text == '\t') {
1380 text++;
1381 offset--;
1382 }
1383 }
1384 PyFile_WriteString(" ", f);
1385 PyFile_WriteString(text, f);
1386 if (*text == '\0' || text[strlen(text)-1] != '\n')
1387 PyFile_WriteString("\n", f);
1388 if (offset == -1)
1389 return;
1390 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001391 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001394}
1395
Guido van Rossum66e8e862001-03-23 17:54:43 +00001396static void
1397handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 PyObject *exception, *value, *tb;
1400 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 if (Py_InspectFlag)
1403 /* Don't exit if -i flag was given. This flag is set to 0
1404 * when entering interactive mode for inspecting. */
1405 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 PyErr_Fetch(&exception, &value, &tb);
1408 fflush(stdout);
1409 if (value == NULL || value == Py_None)
1410 goto done;
1411 if (PyExceptionInstance_Check(value)) {
1412 /* The error code should be in the `code' attribute. */
1413 PyObject *code = PyObject_GetAttrString(value, "code");
1414 if (code) {
1415 Py_DECREF(value);
1416 value = code;
1417 if (value == Py_None)
1418 goto done;
1419 }
1420 /* If we failed to dig out the 'code' attribute,
1421 just let the else clause below print the error. */
1422 }
1423 if (PyLong_Check(value))
1424 exitcode = (int)PyLong_AsLong(value);
1425 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001426 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001427 if (sys_stderr != NULL && sys_stderr != Py_None) {
1428 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1429 } else {
1430 PyObject_Print(value, stderr, Py_PRINT_RAW);
1431 fflush(stderr);
1432 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 PySys_WriteStderr("\n");
1434 exitcode = 1;
1435 }
Tim Peterscf615b52003-04-19 18:47:02 +00001436 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 /* Restore and clear the exception info, in order to properly decref
1438 * the exception, value, and traceback. If we just exit instead,
1439 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1440 * some finalizers from running.
1441 */
1442 PyErr_Restore(exception, value, tb);
1443 PyErr_Clear();
1444 Py_Exit(exitcode);
1445 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001446}
1447
1448void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001449PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1454 handle_system_exit();
1455 }
1456 PyErr_Fetch(&exception, &v, &tb);
1457 if (exception == NULL)
1458 return;
1459 PyErr_NormalizeException(&exception, &v, &tb);
1460 if (tb == NULL) {
1461 tb = Py_None;
1462 Py_INCREF(tb);
1463 }
1464 PyException_SetTraceback(v, tb);
1465 if (exception == NULL)
1466 return;
1467 /* Now we know v != NULL too */
1468 if (set_sys_last_vars) {
1469 PySys_SetObject("last_type", exception);
1470 PySys_SetObject("last_value", v);
1471 PySys_SetObject("last_traceback", tb);
1472 }
1473 hook = PySys_GetObject("excepthook");
1474 if (hook) {
1475 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1476 PyObject *result = PyEval_CallObject(hook, args);
1477 if (result == NULL) {
1478 PyObject *exception2, *v2, *tb2;
1479 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1480 handle_system_exit();
1481 }
1482 PyErr_Fetch(&exception2, &v2, &tb2);
1483 PyErr_NormalizeException(&exception2, &v2, &tb2);
1484 /* It should not be possible for exception2 or v2
1485 to be NULL. However PyErr_Display() can't
1486 tolerate NULLs, so just be safe. */
1487 if (exception2 == NULL) {
1488 exception2 = Py_None;
1489 Py_INCREF(exception2);
1490 }
1491 if (v2 == NULL) {
1492 v2 = Py_None;
1493 Py_INCREF(v2);
1494 }
1495 fflush(stdout);
1496 PySys_WriteStderr("Error in sys.excepthook:\n");
1497 PyErr_Display(exception2, v2, tb2);
1498 PySys_WriteStderr("\nOriginal exception was:\n");
1499 PyErr_Display(exception, v, tb);
1500 Py_DECREF(exception2);
1501 Py_DECREF(v2);
1502 Py_XDECREF(tb2);
1503 }
1504 Py_XDECREF(result);
1505 Py_XDECREF(args);
1506 } else {
1507 PySys_WriteStderr("sys.excepthook is missing\n");
1508 PyErr_Display(exception, v, tb);
1509 }
1510 Py_XDECREF(exception);
1511 Py_XDECREF(v);
1512 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001513}
1514
Benjamin Petersone6528212008-07-15 15:32:09 +00001515static void
1516print_exception(PyObject *f, PyObject *value)
1517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 int err = 0;
1519 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (!PyExceptionInstance_Check(value)) {
1522 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1523 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1524 PyFile_WriteString(" found\n", f);
1525 return;
1526 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 Py_INCREF(value);
1529 fflush(stdout);
1530 type = (PyObject *) Py_TYPE(value);
1531 tb = PyException_GetTraceback(value);
1532 if (tb && tb != Py_None)
1533 err = PyTraceBack_Print(tb, f);
1534 if (err == 0 &&
1535 PyObject_HasAttrString(value, "print_file_and_line"))
1536 {
1537 PyObject *message;
1538 const char *filename, *text;
1539 int lineno, offset;
1540 if (!parse_syntax_error(value, &message, &filename,
1541 &lineno, &offset, &text))
1542 PyErr_Clear();
1543 else {
1544 char buf[10];
1545 PyFile_WriteString(" File \"", f);
1546 if (filename == NULL)
1547 PyFile_WriteString("<string>", f);
1548 else
1549 PyFile_WriteString(filename, f);
1550 PyFile_WriteString("\", line ", f);
1551 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1552 PyFile_WriteString(buf, f);
1553 PyFile_WriteString("\n", f);
1554 if (text != NULL)
1555 print_error_text(f, offset, text);
1556 Py_DECREF(value);
1557 value = message;
1558 /* Can't be bothered to check all those
1559 PyFile_WriteString() calls */
1560 if (PyErr_Occurred())
1561 err = -1;
1562 }
1563 }
1564 if (err) {
1565 /* Don't do anything else */
1566 }
1567 else {
1568 PyObject* moduleName;
1569 char* className;
1570 assert(PyExceptionClass_Check(type));
1571 className = PyExceptionClass_Name(type);
1572 if (className != NULL) {
1573 char *dot = strrchr(className, '.');
1574 if (dot != NULL)
1575 className = dot+1;
1576 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 moduleName = PyObject_GetAttrString(type, "__module__");
1579 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1580 {
1581 Py_DECREF(moduleName);
1582 err = PyFile_WriteString("<unknown>", f);
1583 }
1584 else {
1585 char* modstr = _PyUnicode_AsString(moduleName);
1586 if (modstr && strcmp(modstr, "builtins"))
1587 {
1588 err = PyFile_WriteString(modstr, f);
1589 err += PyFile_WriteString(".", f);
1590 }
1591 Py_DECREF(moduleName);
1592 }
1593 if (err == 0) {
1594 if (className == NULL)
1595 err = PyFile_WriteString("<unknown>", f);
1596 else
1597 err = PyFile_WriteString(className, f);
1598 }
1599 }
1600 if (err == 0 && (value != Py_None)) {
1601 PyObject *s = PyObject_Str(value);
1602 /* only print colon if the str() of the
1603 object is not the empty string
1604 */
1605 if (s == NULL)
1606 err = -1;
1607 else if (!PyUnicode_Check(s) ||
1608 PyUnicode_GetSize(s) != 0)
1609 err = PyFile_WriteString(": ", f);
1610 if (err == 0)
1611 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1612 Py_XDECREF(s);
1613 }
1614 /* try to write a newline in any case */
1615 err += PyFile_WriteString("\n", f);
1616 Py_XDECREF(tb);
1617 Py_DECREF(value);
1618 /* If an error happened here, don't show it.
1619 XXX This is wrong, but too many callers rely on this behavior. */
1620 if (err != 0)
1621 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001622}
1623
1624static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 "\nThe above exception was the direct cause "
1626 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001627
1628static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 "\nDuring handling of the above exception, "
1630 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001631
1632static void
1633print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 int err = 0, res;
1636 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 if (seen != NULL) {
1639 /* Exception chaining */
1640 if (PySet_Add(seen, value) == -1)
1641 PyErr_Clear();
1642 else if (PyExceptionInstance_Check(value)) {
1643 cause = PyException_GetCause(value);
1644 context = PyException_GetContext(value);
1645 if (cause) {
1646 res = PySet_Contains(seen, cause);
1647 if (res == -1)
1648 PyErr_Clear();
1649 if (res == 0) {
1650 print_exception_recursive(
1651 f, cause, seen);
1652 err |= PyFile_WriteString(
1653 cause_message, f);
1654 }
1655 }
1656 else if (context) {
1657 res = PySet_Contains(seen, context);
1658 if (res == -1)
1659 PyErr_Clear();
1660 if (res == 0) {
1661 print_exception_recursive(
1662 f, context, seen);
1663 err |= PyFile_WriteString(
1664 context_message, f);
1665 }
1666 }
1667 Py_XDECREF(context);
1668 Py_XDECREF(cause);
1669 }
1670 }
1671 print_exception(f, value);
1672 if (err != 0)
1673 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001674}
1675
Thomas Wouters477c8d52006-05-27 19:21:47 +00001676void
1677PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 PyObject *seen;
1680 PyObject *f = PySys_GetObject("stderr");
1681 if (f == Py_None) {
1682 /* pass */
1683 }
1684 else if (f == NULL) {
1685 _PyObject_Dump(value);
1686 fprintf(stderr, "lost sys.stderr\n");
1687 }
1688 else {
1689 /* We choose to ignore seen being possibly NULL, and report
1690 at least the main exception (it could be a MemoryError).
1691 */
1692 seen = PySet_New(NULL);
1693 if (seen == NULL)
1694 PyErr_Clear();
1695 print_exception_recursive(f, value, seen);
1696 Py_XDECREF(seen);
1697 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001698}
1699
Guido van Rossum82598051997-03-05 00:20:32 +00001700PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001701PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 PyObject *ret = NULL;
1705 mod_ty mod;
1706 PyArena *arena = PyArena_New();
1707 if (arena == NULL)
1708 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1711 if (mod != NULL)
1712 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1713 PyArena_Free(arena);
1714 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001715}
1716
1717PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001718PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 PyObject *ret;
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_ASTFromFile(fp, filename, NULL, start, 0, 0,
1728 flags, NULL, arena);
1729 if (closeit)
1730 fclose(fp);
1731 if (mod == NULL) {
1732 PyArena_Free(arena);
1733 return NULL;
1734 }
1735 ret = run_mod(mod, filename, globals, locals, flags, arena);
1736 PyArena_Free(arena);
1737 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001738}
1739
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001740static void
1741flush_io(void)
1742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 PyObject *f, *r;
1744 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 /* Save the current exception */
1747 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 f = PySys_GetObject("stderr");
1750 if (f != NULL) {
1751 r = PyObject_CallMethod(f, "flush", "");
1752 if (r)
1753 Py_DECREF(r);
1754 else
1755 PyErr_Clear();
1756 }
1757 f = PySys_GetObject("stdout");
1758 if (f != NULL) {
1759 r = PyObject_CallMethod(f, "flush", "");
1760 if (r)
1761 Py_DECREF(r);
1762 else
1763 PyErr_Clear();
1764 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001767}
1768
Guido van Rossum82598051997-03-05 00:20:32 +00001769static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 PyCodeObject *co;
1774 PyObject *v;
1775 co = PyAST_Compile(mod, filename, flags, arena);
1776 if (co == NULL)
1777 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001778 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 Py_DECREF(co);
1780 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001781}
1782
Guido van Rossum82598051997-03-05 00:20:32 +00001783static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001784run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001786{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 PyCodeObject *co;
1788 PyObject *v;
1789 long magic;
1790 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 magic = PyMarshal_ReadLongFromFile(fp);
1793 if (magic != PyImport_GetMagicNumber()) {
1794 PyErr_SetString(PyExc_RuntimeError,
1795 "Bad magic number in .pyc file");
1796 return NULL;
1797 }
1798 (void) PyMarshal_ReadLongFromFile(fp);
1799 v = PyMarshal_ReadLastObjectFromFile(fp);
1800 fclose(fp);
1801 if (v == NULL || !PyCode_Check(v)) {
1802 Py_XDECREF(v);
1803 PyErr_SetString(PyExc_RuntimeError,
1804 "Bad code object in .pyc file");
1805 return NULL;
1806 }
1807 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001808 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 if (v && flags)
1810 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1811 Py_DECREF(co);
1812 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001813}
1814
Guido van Rossum82598051997-03-05 00:20:32 +00001815PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001816Py_CompileStringExFlags(const char *str, const char *filename, int start,
1817 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 PyCodeObject *co;
1820 mod_ty mod;
1821 PyArena *arena = PyArena_New();
1822 if (arena == NULL)
1823 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1826 if (mod == NULL) {
1827 PyArena_Free(arena);
1828 return NULL;
1829 }
1830 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1831 PyObject *result = PyAST_mod2obj(mod);
1832 PyArena_Free(arena);
1833 return result;
1834 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001835 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 PyArena_Free(arena);
1837 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001838}
1839
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001840/* For use in Py_LIMITED_API */
1841#undef Py_CompileString
1842PyObject *
1843PyCompileString(const char *str, const char *filename, int start)
1844{
1845 return Py_CompileStringFlags(str, filename, start, NULL);
1846}
1847
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001848struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001849Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 struct symtable *st;
1852 mod_ty mod;
1853 PyCompilerFlags flags;
1854 PyArena *arena = PyArena_New();
1855 if (arena == NULL)
1856 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 flags.cf_flags = 0;
1859 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1860 if (mod == NULL) {
1861 PyArena_Free(arena);
1862 return NULL;
1863 }
1864 st = PySymtable_Build(mod, filename, 0);
1865 PyArena_Free(arena);
1866 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001867}
1868
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001869/* Preferred access to parser is through AST. */
1870mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001871PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 mod_ty mod;
1875 PyCompilerFlags localflags;
1876 perrdetail err;
1877 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1880 &_PyParser_Grammar, start, &err,
1881 &iflags);
1882 if (flags == NULL) {
1883 localflags.cf_flags = 0;
1884 flags = &localflags;
1885 }
1886 if (n) {
1887 flags->cf_flags |= iflags & PyCF_MASK;
1888 mod = PyAST_FromNode(n, flags, filename, arena);
1889 PyNode_Free(n);
1890 return mod;
1891 }
1892 else {
1893 err_input(&err);
1894 return NULL;
1895 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001896}
1897
1898mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001899PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 int start, char *ps1,
1901 char *ps2, PyCompilerFlags *flags, int *errcode,
1902 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 mod_ty mod;
1905 PyCompilerFlags localflags;
1906 perrdetail err;
1907 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1910 &_PyParser_Grammar,
1911 start, ps1, ps2, &err, &iflags);
1912 if (flags == NULL) {
1913 localflags.cf_flags = 0;
1914 flags = &localflags;
1915 }
1916 if (n) {
1917 flags->cf_flags |= iflags & PyCF_MASK;
1918 mod = PyAST_FromNode(n, flags, filename, arena);
1919 PyNode_Free(n);
1920 return mod;
1921 }
1922 else {
1923 err_input(&err);
1924 if (errcode)
1925 *errcode = err.error;
1926 return NULL;
1927 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001928}
1929
Guido van Rossuma110aa61994-08-29 12:50:44 +00001930/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001931
Guido van Rossuma110aa61994-08-29 12:50:44 +00001932node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001933PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 perrdetail err;
1936 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1937 &_PyParser_Grammar,
1938 start, NULL, NULL, &err, flags);
1939 if (n == NULL)
1940 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001943}
1944
Guido van Rossuma110aa61994-08-29 12:50:44 +00001945/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001946
Guido van Rossuma110aa61994-08-29 12:50:44 +00001947node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001948PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 perrdetail err;
1951 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1952 start, &err, flags);
1953 if (n == NULL)
1954 err_input(&err);
1955 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001956}
1957
1958node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001959PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 perrdetail err;
1963 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1964 &_PyParser_Grammar, start, &err, flags);
1965 if (n == NULL)
1966 err_input(&err);
1967 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001968}
1969
1970node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001971PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001974}
1975
Guido van Rossum66ebd912003-04-17 16:02:26 +00001976/* May want to move a more generalized form of this to parsetok.c or
1977 even parser modules. */
1978
1979void
1980PyParser_SetError(perrdetail *err)
1981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001983}
1984
Guido van Rossuma110aa61994-08-29 12:50:44 +00001985/* Set the error appropriate to the given input error code (see errcode.h) */
1986
1987static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001988err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 PyObject *v, *w, *errtype, *errtext;
1991 PyObject *msg_obj = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001992 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 errtype = PyExc_SyntaxError;
1996 switch (err->error) {
1997 case E_ERROR:
1998 return;
1999 case E_SYNTAX:
2000 errtype = PyExc_IndentationError;
2001 if (err->expected == INDENT)
2002 msg = "expected an indented block";
2003 else if (err->token == INDENT)
2004 msg = "unexpected indent";
2005 else if (err->token == DEDENT)
2006 msg = "unexpected unindent";
2007 else {
2008 errtype = PyExc_SyntaxError;
2009 msg = "invalid syntax";
2010 }
2011 break;
2012 case E_TOKEN:
2013 msg = "invalid token";
2014 break;
2015 case E_EOFS:
2016 msg = "EOF while scanning triple-quoted string literal";
2017 break;
2018 case E_EOLS:
2019 msg = "EOL while scanning string literal";
2020 break;
2021 case E_INTR:
2022 if (!PyErr_Occurred())
2023 PyErr_SetNone(PyExc_KeyboardInterrupt);
2024 goto cleanup;
2025 case E_NOMEM:
2026 PyErr_NoMemory();
2027 goto cleanup;
2028 case E_EOF:
2029 msg = "unexpected EOF while parsing";
2030 break;
2031 case E_TABSPACE:
2032 errtype = PyExc_TabError;
2033 msg = "inconsistent use of tabs and spaces in indentation";
2034 break;
2035 case E_OVERFLOW:
2036 msg = "expression too long";
2037 break;
2038 case E_DEDENT:
2039 errtype = PyExc_IndentationError;
2040 msg = "unindent does not match any outer indentation level";
2041 break;
2042 case E_TOODEEP:
2043 errtype = PyExc_IndentationError;
2044 msg = "too many levels of indentation";
2045 break;
2046 case E_DECODE: {
2047 PyObject *type, *value, *tb;
2048 PyErr_Fetch(&type, &value, &tb);
2049 msg = "unknown decode error";
2050 if (value != NULL)
2051 msg_obj = PyObject_Str(value);
2052 Py_XDECREF(type);
2053 Py_XDECREF(value);
2054 Py_XDECREF(tb);
2055 break;
2056 }
2057 case E_LINECONT:
2058 msg = "unexpected character after line continuation character";
2059 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 case E_IDENTIFIER:
2062 msg = "invalid character in identifier";
2063 break;
2064 default:
2065 fprintf(stderr, "error=%d\n", err->error);
2066 msg = "unknown parsing error";
2067 break;
2068 }
2069 /* err->text may not be UTF-8 in case of decoding errors.
2070 Explicitly convert to an object. */
2071 if (!err->text) {
2072 errtext = Py_None;
2073 Py_INCREF(Py_None);
2074 } else {
2075 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2076 "replace");
2077 }
Victor Stinner2f2ed1f2010-10-16 13:42:53 +00002078 if (err->filename != NULL)
2079 filename = PyUnicode_DecodeFSDefault(err->filename);
2080 else {
2081 Py_INCREF(Py_None);
2082 filename = Py_None;
2083 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002084 if (filename != NULL)
2085 v = Py_BuildValue("(NiiN)", filename,
2086 err->lineno, err->offset, errtext);
2087 else
2088 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (v != NULL) {
2090 if (msg_obj)
2091 w = Py_BuildValue("(OO)", msg_obj, v);
2092 else
2093 w = Py_BuildValue("(sO)", msg, v);
2094 } else
2095 w = NULL;
2096 Py_XDECREF(v);
2097 PyErr_SetObject(errtype, w);
2098 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002099cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 Py_XDECREF(msg_obj);
2101 if (err->text != NULL) {
2102 PyObject_FREE(err->text);
2103 err->text = NULL;
2104 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002105}
2106
2107/* Print fatal error message and abort */
2108
2109void
Tim Peters7c321a82002-07-09 02:57:01 +00002110Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002111{
Victor Stinner024e37a2011-03-31 01:31:06 +02002112 const int fd = fileno(stderr);
2113 PyThreadState *tstate;
2114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 fprintf(stderr, "Fatal Python error: %s\n", msg);
2116 fflush(stderr); /* it helps in Windows debug build */
2117 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002118 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002120 else {
2121 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2122 if (tstate != NULL) {
2123 fputc('\n', stderr);
2124 fflush(stderr);
2125 _Py_DumpTraceback(fd, tstate);
2126 }
2127 }
2128
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002129#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 {
2131 size_t len = strlen(msg);
2132 WCHAR* buffer;
2133 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 /* Convert the message to wchar_t. This uses a simple one-to-one
2136 conversion, assuming that the this error message actually uses ASCII
2137 only. If this ceases to be true, we will have to convert. */
2138 buffer = alloca( (len+1) * (sizeof *buffer));
2139 for( i=0; i<=len; ++i)
2140 buffer[i] = msg[i];
2141 OutputDebugStringW(L"Fatal Python error: ");
2142 OutputDebugStringW(buffer);
2143 OutputDebugStringW(L"\n");
2144 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002145#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002147#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002148#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002150}
2151
2152/* Clean up and exit */
2153
Guido van Rossuma110aa61994-08-29 12:50:44 +00002154#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002155#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002156#endif
2157
Collin Winter670e6922007-03-21 02:57:17 +00002158static void (*pyexitfunc)(void) = NULL;
2159/* For the atexit module. */
2160void _Py_PyAtExit(void (*func)(void))
2161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002163}
2164
2165static void
2166call_py_exitfuncs(void)
2167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 if (pyexitfunc == NULL)
2169 return;
Collin Winter670e6922007-03-21 02:57:17 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 (*pyexitfunc)();
2172 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002173}
2174
Antoine Pitrou011bd622009-10-20 21:52:47 +00002175/* Wait until threading._shutdown completes, provided
2176 the threading module was imported in the first place.
2177 The shutdown routine will wait until all non-daemon
2178 "threading" threads have completed. */
2179static void
2180wait_for_thread_shutdown(void)
2181{
2182#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 PyObject *result;
2184 PyThreadState *tstate = PyThreadState_GET();
2185 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2186 "threading");
2187 if (threading == NULL) {
2188 /* threading not imported */
2189 PyErr_Clear();
2190 return;
2191 }
2192 result = PyObject_CallMethod(threading, "_shutdown", "");
2193 if (result == NULL) {
2194 PyErr_WriteUnraisable(threading);
2195 }
2196 else {
2197 Py_DECREF(result);
2198 }
2199 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002200#endif
2201}
2202
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002203#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002204static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002205static int nexitfuncs = 0;
2206
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002207int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 if (nexitfuncs >= NEXITFUNCS)
2210 return -1;
2211 exitfuncs[nexitfuncs++] = func;
2212 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002213}
2214
Guido van Rossumcc283f51997-08-05 02:22:03 +00002215static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002216call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 while (nexitfuncs > 0)
2219 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 fflush(stdout);
2222 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002223}
2224
2225void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002226Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002231}
2232
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002233static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002234initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002235{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002236#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002238#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002239#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002241#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002242#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002244#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002246}
2247
Guido van Rossum7433b121997-02-14 19:45:36 +00002248
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002249/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2250 *
2251 * All of the code in this function must only use async-signal-safe functions,
2252 * listed at `man 7 signal` or
2253 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2254 */
2255void
2256_Py_RestoreSignals(void)
2257{
2258#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002260#endif
2261#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002263#endif
2264#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002266#endif
2267}
2268
2269
Guido van Rossum7433b121997-02-14 19:45:36 +00002270/*
2271 * The file descriptor fd is considered ``interactive'' if either
2272 * a) isatty(fd) is TRUE, or
2273 * b) the -i flag was given, and the filename associated with
2274 * the descriptor is NULL or "<stdin>" or "???".
2275 */
2276int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002277Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 if (isatty((int)fileno(fp)))
2280 return 1;
2281 if (!Py_InteractiveFlag)
2282 return 0;
2283 return (filename == NULL) ||
2284 (strcmp(filename, "<stdin>") == 0) ||
2285 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002286}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002287
2288
Tim Petersd08e3822003-04-17 15:24:21 +00002289#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002290#if defined(WIN32) && defined(_MSC_VER)
2291
2292/* Stack checking for Microsoft C */
2293
2294#include <malloc.h>
2295#include <excpt.h>
2296
Fred Drakee8de31c2000-08-31 05:38:39 +00002297/*
2298 * Return non-zero when we run out of memory on the stack; zero otherwise.
2299 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002300int
Fred Drake399739f2000-08-31 05:52:44 +00002301PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 __try {
2304 /* alloca throws a stack overflow exception if there's
2305 not enough space left on the stack */
2306 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2307 return 0;
2308 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2309 EXCEPTION_EXECUTE_HANDLER :
2310 EXCEPTION_CONTINUE_SEARCH) {
2311 int errcode = _resetstkoflw();
2312 if (errcode == 0)
2313 {
2314 Py_FatalError("Could not reset the stack!");
2315 }
2316 }
2317 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002318}
2319
2320#endif /* WIN32 && _MSC_VER */
2321
2322/* Alternate implementations can be added here... */
2323
2324#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002325
2326
2327/* Wrappers around sigaction() or signal(). */
2328
2329PyOS_sighandler_t
2330PyOS_getsig(int sig)
2331{
2332#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 struct sigaction context;
2334 if (sigaction(sig, NULL, &context) == -1)
2335 return SIG_ERR;
2336 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002337#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002339/* Special signal handling for the secure CRT in Visual Studio 2005 */
2340#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 switch (sig) {
2342 /* Only these signals are valid */
2343 case SIGINT:
2344 case SIGILL:
2345 case SIGFPE:
2346 case SIGSEGV:
2347 case SIGTERM:
2348 case SIGBREAK:
2349 case SIGABRT:
2350 break;
2351 /* Don't call signal() with other values or it will assert */
2352 default:
2353 return SIG_ERR;
2354 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002355#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 handler = signal(sig, SIG_IGN);
2357 if (handler != SIG_ERR)
2358 signal(sig, handler);
2359 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002360#endif
2361}
2362
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002363/*
2364 * All of the code in this function must only use async-signal-safe functions,
2365 * listed at `man 7 signal` or
2366 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2367 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002368PyOS_sighandler_t
2369PyOS_setsig(int sig, PyOS_sighandler_t handler)
2370{
2371#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 /* Some code in Modules/signalmodule.c depends on sigaction() being
2373 * used here if HAVE_SIGACTION is defined. Fix that if this code
2374 * changes to invalidate that assumption.
2375 */
2376 struct sigaction context, ocontext;
2377 context.sa_handler = handler;
2378 sigemptyset(&context.sa_mask);
2379 context.sa_flags = 0;
2380 if (sigaction(sig, &context, &ocontext) == -1)
2381 return SIG_ERR;
2382 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002383#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 PyOS_sighandler_t oldhandler;
2385 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002386#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002388#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002390#endif
2391}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002392
2393/* Deprecated C API functions still provided for binary compatiblity */
2394
2395#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002396PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002400}
2401
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002402#undef PyParser_SimpleParseString
2403PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002404PyParser_SimpleParseString(const char *str, int start)
2405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002407}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002408
2409#undef PyRun_AnyFile
2410PyAPI_FUNC(int)
2411PyRun_AnyFile(FILE *fp, const char *name)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002414}
2415
2416#undef PyRun_AnyFileEx
2417PyAPI_FUNC(int)
2418PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002421}
2422
2423#undef PyRun_AnyFileFlags
2424PyAPI_FUNC(int)
2425PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002428}
2429
2430#undef PyRun_File
2431PyAPI_FUNC(PyObject *)
2432PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002435}
2436
2437#undef PyRun_FileEx
2438PyAPI_FUNC(PyObject *)
2439PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002442}
2443
2444#undef PyRun_FileFlags
2445PyAPI_FUNC(PyObject *)
2446PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002450}
2451
2452#undef PyRun_SimpleFile
2453PyAPI_FUNC(int)
2454PyRun_SimpleFile(FILE *f, const char *p)
2455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002457}
2458
2459#undef PyRun_SimpleFileEx
2460PyAPI_FUNC(int)
2461PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002464}
2465
2466
2467#undef PyRun_String
2468PyAPI_FUNC(PyObject *)
2469PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002472}
2473
2474#undef PyRun_SimpleString
2475PyAPI_FUNC(int)
2476PyRun_SimpleString(const char *s)
2477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002479}
2480
2481#undef Py_CompileString
2482PyAPI_FUNC(PyObject *)
2483Py_CompileString(const char *str, const char *p, int s)
2484{
Georg Brandl8334fd92010-12-04 10:26:46 +00002485 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2486}
2487
2488#undef Py_CompileStringFlags
2489PyAPI_FUNC(PyObject *)
2490Py_CompileStringFlags(const char *str, const char *p, int s,
2491 PyCompilerFlags *flags)
2492{
2493 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002494}
2495
2496#undef PyRun_InteractiveOne
2497PyAPI_FUNC(int)
2498PyRun_InteractiveOne(FILE *f, const char *p)
2499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002501}
2502
2503#undef PyRun_InteractiveLoop
2504PyAPI_FUNC(int)
2505PyRun_InteractiveLoop(FILE *f, const char *p)
2506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002508}
2509
2510#ifdef __cplusplus
2511}
2512#endif