blob: faaf54a0a67626d0cdaa4ee7b9028c5fae74be3e [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 Stinner3cbf14b2011-04-27 00:24:21 +020056static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
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);
Guido van Rossumc94044c2000-03-10 23:03:54 +000073
Mark Hammond8d98d2c2003-04-19 15:41:53 +000074#ifdef WITH_THREAD
75extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
76extern void _PyGILState_Fini(void);
77#endif /* WITH_THREAD */
78
Guido van Rossum82598051997-03-05 00:20:32 +000079int Py_DebugFlag; /* Needed by parser.c */
80int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000081int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000082int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000083int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000084int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000085int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000086int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000087int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000088int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000089int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000090int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000091int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000092
Christian Heimes33fe8092008-04-13 13:53:33 +000093/* PyModule_GetWarningsModule is no longer necessary as of 2.6
94since _warnings is builtin. This API should not be used. */
95PyObject *
96PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000099}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000100
Guido van Rossum25ce5661997-08-02 03:10:38 +0000101static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000102
Thomas Wouters7e474022000-07-16 12:04:32 +0000103/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000104
105int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000106Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109}
110
Guido van Rossum25ce5661997-08-02 03:10:38 +0000111/* Global initializations. Can be undone by Py_Finalize(). Don't
112 call this twice without an intervening Py_Finalize() call. When
113 initializations fail, a fatal error is issued and the function does
114 not return. On return, the first thread and interpreter state have
115 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117 Locking: you must hold the interpreter lock while calling this.
118 (If the lock has not yet been initialized, that's equivalent to
119 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000122
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000123static int
124add_flag(int flag, const char *envs)
125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 int env = atoi(envs);
127 if (flag < env)
128 flag = env;
129 if (flag < 1)
130 flag = 1;
131 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000132}
133
Christian Heimes5833a2f2008-10-30 21:40:04 +0000134static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000135get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000136{
Victor Stinner94908bb2010-08-18 21:23:25 +0000137 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000138 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000139
Victor Stinner94908bb2010-08-18 21:23:25 +0000140 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 if (!codec)
142 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 name = PyObject_GetAttrString(codec, "name");
145 Py_CLEAR(codec);
146 if (!name)
147 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000148
Victor Stinner94908bb2010-08-18 21:23:25 +0000149 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner9c4efe52011-03-20 23:23:22 +0100150 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000151 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000152 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000154 if (name_str == NULL) {
155 PyErr_NoMemory();
156 return NULL;
157 }
158 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000159
160error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000162 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000164}
Victor Stinner94908bb2010-08-18 21:23:25 +0000165
166#if defined(HAVE_LANGINFO_H) && defined(CODESET)
167static char*
168get_codeset(void)
169{
170 char* codeset = nl_langinfo(CODESET);
171 if (!codeset || codeset[0] == '\0') {
172 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
173 return NULL;
174 }
175 return get_codec_name(codeset);
176}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000177#endif
178
Guido van Rossuma027efa1997-05-05 20:56:21 +0000179void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000180Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 PyInterpreterState *interp;
183 PyThreadState *tstate;
184 PyObject *bimod, *sysmod, *pstderr;
185 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (initialized)
189 return;
190 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000191
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000192#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 /* Set up the LC_CTYPE locale, so we can obtain
194 the locale's charset without having to switch
195 locales. */
196 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000197#endif
198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
200 Py_DebugFlag = add_flag(Py_DebugFlag, p);
201 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
202 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
203 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
204 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
205 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
206 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 interp = PyInterpreterState_New();
209 if (interp == NULL)
210 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 tstate = PyThreadState_New(interp);
213 if (tstate == NULL)
214 Py_FatalError("Py_Initialize: can't make first thread");
215 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000216
Victor Stinner6961bd62010-08-17 22:26:51 +0000217#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000218 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
219 destroying the GIL might fail when it is being referenced from
220 another running thread (see issue #9901).
221 Instead we destroy the previously created GIL here, which ensures
222 that we can call Py_Initialize / Py_Finalize multiple times. */
223 _PyEval_FiniThreads();
224
225 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000226 _PyGILState_Init(interp, tstate);
227#endif /* WITH_THREAD */
228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (!_PyFrame_Init())
232 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (!_PyLong_Init())
235 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (!PyByteArray_Init())
238 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 interp->modules = PyDict_New();
243 if (interp->modules == NULL)
244 Py_FatalError("Py_Initialize: can't make modules dictionary");
245 interp->modules_reloading = PyDict_New();
246 if (interp->modules_reloading == NULL)
247 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 /* Init Unicode implementation; relies on the codec registry */
250 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 bimod = _PyBuiltin_Init();
253 if (bimod == NULL)
254 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000255 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 interp->builtins = PyModule_GetDict(bimod);
257 if (interp->builtins == NULL)
258 Py_FatalError("Py_Initialize: can't initialize builtins dict");
259 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 /* initialize builtin exceptions */
262 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 sysmod = _PySys_Init();
265 if (sysmod == NULL)
266 Py_FatalError("Py_Initialize: can't initialize sys");
267 interp->sysdict = PyModule_GetDict(sysmod);
268 if (interp->sysdict == NULL)
269 Py_FatalError("Py_Initialize: can't initialize sys dict");
270 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000271 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 PySys_SetPath(Py_GetPath());
273 PyDict_SetItemString(interp->sysdict, "modules",
274 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* Set up a preliminary stderr printer until we have enough
277 infrastructure for the io module in place. */
278 pstderr = PyFile_NewStdPrinter(fileno(stderr));
279 if (pstderr == NULL)
280 Py_FatalError("Py_Initialize: can't set preliminary stderr");
281 PySys_SetObject("stderr", pstderr);
282 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000283 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000288
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000289 /* Initialize _warnings. */
290 _PyWarnings_Init();
291
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000292 _PyTime_Init();
293
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200294 if (initfsencoding(interp) < 0)
295 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 if (install_sigs)
298 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 initmain(); /* Module __main__ */
301 if (initstdio() < 0)
302 Py_FatalError(
303 "Py_Initialize: can't initialize sys standard streams");
304
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000305 /* Initialize warnings. */
306 if (PySys_HasWarnOptions()) {
307 PyObject *warnings_module = PyImport_ImportModule("warnings");
308 if (warnings_module == NULL) {
309 fprintf(stderr, "'import warnings' failed; traceback:\n");
310 PyErr_Print();
311 }
312 Py_XDECREF(warnings_module);
313 }
314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (!Py_NoSiteFlag)
316 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000317}
318
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000319void
320Py_Initialize(void)
321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000323}
324
325
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000326#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000327extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000328#endif
329
Guido van Rossume8432ac2007-07-09 15:04:50 +0000330/* Flush stdout and stderr */
331
Neal Norwitz2bad9702007-08-27 06:19:22 +0000332static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000333flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 PyObject *fout = PySys_GetObject("stdout");
336 PyObject *ferr = PySys_GetObject("stderr");
337 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (fout != NULL && fout != Py_None) {
340 tmp = PyObject_CallMethod(fout, "flush", "");
341 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000342 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 else
344 Py_DECREF(tmp);
345 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000346
Victor Stinner9467b212010-05-14 00:59:09 +0000347 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 tmp = PyObject_CallMethod(ferr, "flush", "");
349 if (tmp == NULL)
350 PyErr_Clear();
351 else
352 Py_DECREF(tmp);
353 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000354}
355
Guido van Rossum25ce5661997-08-02 03:10:38 +0000356/* Undo the effect of Py_Initialize().
357
358 Beware: if multiple interpreter and/or thread states exist, these
359 are not wiped out; only the current thread and interpreter state
360 are deleted. But since everything else is deleted, those other
361 interpreter and thread states should no longer be used.
362
363 (XXX We should do better, e.g. wipe out all interpreters and
364 threads.)
365
366 Locking: as above.
367
368*/
369
370void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000371Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 PyInterpreterState *interp;
374 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 if (!initialized)
377 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 /* The interpreter is still entirely intact at this point, and the
382 * exit funcs may be relying on that. In particular, if some thread
383 * or exit func is still waiting to do an import, the import machinery
384 * expects Py_IsInitialized() to return true. So don't say the
385 * interpreter is uninitialized until after the exit funcs have run.
386 * Note that Threading.py uses an exit func to do a join on all the
387 * threads created thru it, so this also protects pending imports in
388 * the threads created via Threading.
389 */
390 call_py_exitfuncs();
391 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* Flush stdout+stderr */
394 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 /* Get current thread state and interpreter pointer */
397 tstate = PyThreadState_GET();
398 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 /* Disable signal handling */
401 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 /* Clear type lookup cache */
404 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 /* Collect garbage. This may call finalizers; it's nice to call these
407 * before all modules are destroyed.
408 * XXX If a __del__ or weakref callback is triggered here, and tries to
409 * XXX import a module, bad things can happen, because Python no
410 * XXX longer believes it's initialized.
411 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
412 * XXX is easy to provoke that way. I've also seen, e.g.,
413 * XXX Exception exceptions.ImportError: 'No module named sha'
414 * XXX in <function callback at 0x008F5718> ignored
415 * XXX but I'm unclear on exactly how that one happens. In any case,
416 * XXX I haven't seen a real-life report of either of these.
417 */
418 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000419#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 /* With COUNT_ALLOCS, it helps to run GC multiple times:
421 each collection might release some types from the type
422 list, so they become garbage. */
423 while (PyGC_Collect() > 0)
424 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000425#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000426 /* We run this while most interpreter state is still alive, so that
427 debug information can be printed out */
428 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 /* Destroy all modules */
431 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 /* Flush stdout+stderr (again, in case more was printed) */
434 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 /* Collect final garbage. This disposes of cycles created by
437 * new-style class definitions, for example.
438 * XXX This is disabled because it caused too many problems. If
439 * XXX a __del__ or weakref callback triggers here, Python code has
440 * XXX a hard time running, because even the sys module has been
441 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
442 * XXX One symptom is a sequence of information-free messages
443 * XXX coming from threads (if a __del__ or callback is invoked,
444 * XXX other threads can execute too, and any exception they encounter
445 * XXX triggers a comedy of errors as subsystem after subsystem
446 * XXX fails to find what it *expects* to find in sys to help report
447 * XXX the exception and consequent unexpected failures). I've also
448 * XXX seen segfaults then, after adding print statements to the
449 * XXX Python code getting called.
450 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000451#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000453#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
456 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000459#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000461#endif
462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000464
Tim Peters9cf25ce2003-04-17 15:21:01 +0000465#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 /* Display all objects still alive -- this can invoke arbitrary
467 * __repr__ overrides, so requires a mostly-intact interpreter.
468 * Alas, a lot of stuff may still be alive now that will be cleaned
469 * up later.
470 */
471 if (Py_GETENV("PYTHONDUMPREFS"))
472 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000473#endif /* Py_TRACE_REFS */
474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 /* Clear interpreter state */
476 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* Now we decref the exception classes. After this point nothing
479 can raise an exception. That's okay, because each Fini() method
480 below has been checked to make sure no exceptions are ever
481 raised.
482 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000487#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000489#endif /* WITH_THREAD */
490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 /* Delete current thread */
492 PyThreadState_Swap(NULL);
493 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* Sundry finalizers */
496 PyMethod_Fini();
497 PyFrame_Fini();
498 PyCFunction_Fini();
499 PyTuple_Fini();
500 PyList_Fini();
501 PySet_Fini();
502 PyBytes_Fini();
503 PyByteArray_Fini();
504 PyLong_Fini();
505 PyFloat_Fini();
506 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 /* Cleanup Unicode implementation */
509 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000512 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 free((char*)Py_FileSystemDefaultEncoding);
514 Py_FileSystemDefaultEncoding = NULL;
515 }
Christian Heimesc8967002007-11-30 10:18:26 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* XXX Still allocated:
518 - various static ad-hoc pointers to interned strings
519 - int and float free list blocks
520 - whatever various modules and libraries allocate
521 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000524
Tim Peters269b2a62003-04-17 19:52:29 +0000525#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* Display addresses (& refcnts) of all objects still alive.
527 * An address can be used to find the repr of the object, printed
528 * above by _Py_PrintReferences.
529 */
530 if (Py_GETENV("PYTHONDUMPREFS"))
531 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000532#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000533#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (Py_GETENV("PYTHONMALLOCSTATS"))
535 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000536#endif
537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000539}
540
541/* Create and initialize a new interpreter and thread, and return the
542 new thread. This requires that Py_Initialize() has been called
543 first.
544
545 Unsuccessful initialization yields a NULL pointer. Note that *no*
546 exception information is available even in this case -- the
547 exception information is held in the thread, and there is no
548 thread.
549
550 Locking: as above.
551
552*/
553
554PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000555Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 PyInterpreterState *interp;
558 PyThreadState *tstate, *save_tstate;
559 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (!initialized)
562 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 interp = PyInterpreterState_New();
565 if (interp == NULL)
566 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 tstate = PyThreadState_New(interp);
569 if (tstate == NULL) {
570 PyInterpreterState_Delete(interp);
571 return NULL;
572 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 interp->modules = PyDict_New();
579 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000580
Victor Stinner49d3f252010-10-17 01:24:53 +0000581 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 if (bimod != NULL) {
583 interp->builtins = PyModule_GetDict(bimod);
584 if (interp->builtins == NULL)
585 goto handle_error;
586 Py_INCREF(interp->builtins);
587 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 /* initialize builtin exceptions */
590 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000591
Victor Stinner49d3f252010-10-17 01:24:53 +0000592 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (bimod != NULL && sysmod != NULL) {
594 PyObject *pstderr;
595 interp->sysdict = PyModule_GetDict(sysmod);
596 if (interp->sysdict == NULL)
597 goto handle_error;
598 Py_INCREF(interp->sysdict);
599 PySys_SetPath(Py_GetPath());
600 PyDict_SetItemString(interp->sysdict, "modules",
601 interp->modules);
602 /* Set up a preliminary stderr printer until we have enough
603 infrastructure for the io module in place. */
604 pstderr = PyFile_NewStdPrinter(fileno(stderr));
605 if (pstderr == NULL)
606 Py_FatalError("Py_Initialize: can't set preliminary stderr");
607 PySys_SetObject("stderr", pstderr);
608 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000609 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 _PyImportHooks_Init();
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200612
613 if (initfsencoding(interp) < 0)
614 goto handle_error;
615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (initstdio() < 0)
617 Py_FatalError(
618 "Py_Initialize: can't initialize sys standard streams");
619 initmain();
620 if (!Py_NoSiteFlag)
621 initsite();
622 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (!PyErr_Occurred())
625 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000626
Thomas Wouters89f507f2006-12-13 04:49:30 +0000627handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629
Victor Stinner11889352011-04-27 00:20:27 +0200630 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 PyThreadState_Clear(tstate);
632 PyThreadState_Swap(save_tstate);
633 PyThreadState_Delete(tstate);
634 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637}
638
639/* Delete an interpreter and its last thread. This requires that the
640 given thread state is current, that the thread has no remaining
641 frames, and that it is its interpreter's only remaining thread.
642 It is a fatal error to violate these constraints.
643
644 (Py_Finalize() doesn't have these constraints -- it zaps
645 everything, regardless.)
646
647 Locking: as above.
648
649*/
650
651void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000652Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (tstate != PyThreadState_GET())
657 Py_FatalError("Py_EndInterpreter: thread is not current");
658 if (tstate->frame != NULL)
659 Py_FatalError("Py_EndInterpreter: thread still has a frame");
660 if (tstate != interp->tstate_head || tstate->next != NULL)
661 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 PyImport_Cleanup();
664 PyInterpreterState_Clear(interp);
665 PyThreadState_Swap(NULL);
666 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000667}
668
Martin v. Löwis790465f2008-04-05 20:41:37 +0000669static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000670
671void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000672Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 if (pn && *pn)
675 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000676}
677
Martin v. Löwis790465f2008-04-05 20:41:37 +0000678wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000679Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000682}
683
Martin v. Löwis790465f2008-04-05 20:41:37 +0000684static wchar_t *default_home = NULL;
685static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000686
687void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000688Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000691}
692
Martin v. Löwis790465f2008-04-05 20:41:37 +0000693wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000694Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 wchar_t *home = default_home;
697 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
698 char* chome = Py_GETENV("PYTHONHOME");
699 if (chome) {
700 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
701 if (r != (size_t)-1 && r <= PATH_MAX)
702 home = env_home;
703 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 }
706 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000707}
708
Guido van Rossum6135a871995-01-09 17:53:26 +0000709/* Create __main__ module */
710
711static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000712initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyObject *m, *d;
715 m = PyImport_AddModule("__main__");
716 if (m == NULL)
717 Py_FatalError("can't create __main__ module");
718 d = PyModule_GetDict(m);
719 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
720 PyObject *bimod = PyImport_ImportModule("builtins");
721 if (bimod == NULL ||
722 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
723 Py_FatalError("can't add __builtins__ to __main__");
724 Py_DECREF(bimod);
725 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000726}
727
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200728static int
729initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000730{
731 PyObject *codec;
732#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000733 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000734
Victor Stinner7f84ab52010-06-11 00:36:33 +0000735 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000736 /* On Unix, set the file system encoding according to the
737 user's preference, if the CODESET names a well-known
738 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000739 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000740 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000741 if (codeset == NULL)
742 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000743
Victor Stinnere4743092010-10-19 00:05:51 +0000744 Py_FileSystemDefaultEncoding = codeset;
745 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200746 interp->fscodec_initialized = 1;
747 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000748 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000749#endif
750
751 /* the encoding is mbcs, utf-8 or ascii */
752 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
753 if (!codec) {
754 /* Such error can only occurs in critical situations: no more
755 * memory, import a module of the standard library failed,
756 * etc. */
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200757 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000758 }
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200759 Py_DECREF(codec);
760 interp->fscodec_initialized = 1;
761 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000762}
763
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000764/* Import the site module (not into __main__ though) */
765
766static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000767initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 PyObject *m;
770 m = PyImport_ImportModule("site");
771 if (m == NULL) {
772 PyErr_Print();
773 Py_Finalize();
774 exit(1);
775 }
776 else {
777 Py_DECREF(m);
778 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000779}
780
Antoine Pitrou05608432009-01-09 18:53:14 +0000781static PyObject*
782create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 int fd, int write_mode, char* name,
784 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
787 const char* mode;
Victor Stinner02bfdb32011-02-23 12:10:23 +0000788 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 PyObject *line_buffering;
790 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 /* stdin is always opened in buffered mode, first because it shouldn't
793 make a difference in common use cases, second because TextIOWrapper
794 depends on the presence of a read1() method which only exists on
795 buffered streams.
796 */
797 if (Py_UnbufferedStdioFlag && write_mode)
798 buffering = 0;
799 else
800 buffering = -1;
801 if (write_mode)
802 mode = "wb";
803 else
804 mode = "rb";
805 buf = PyObject_CallMethod(io, "open", "isiOOOi",
806 fd, mode, buffering,
807 Py_None, Py_None, Py_None, 0);
808 if (buf == NULL)
809 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (buffering) {
812 raw = PyObject_GetAttrString(buf, "raw");
813 if (raw == NULL)
814 goto error;
815 }
816 else {
817 raw = buf;
818 Py_INCREF(raw);
819 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 text = PyUnicode_FromString(name);
822 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
823 goto error;
824 res = PyObject_CallMethod(raw, "isatty", "");
825 if (res == NULL)
826 goto error;
827 isatty = PyObject_IsTrue(res);
828 Py_DECREF(res);
829 if (isatty == -1)
830 goto error;
831 if (isatty || Py_UnbufferedStdioFlag)
832 line_buffering = Py_True;
833 else
834 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 Py_CLEAR(raw);
837 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000838
Victor Stinner02bfdb32011-02-23 12:10:23 +0000839 newline = "\n";
840#ifdef MS_WINDOWS
841 if (!write_mode) {
842 /* translate \r\n to \n for sys.stdin on Windows */
843 newline = NULL;
844 }
845#endif
846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
848 buf, encoding, errors,
Victor Stinner02bfdb32011-02-23 12:10:23 +0000849 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 Py_CLEAR(buf);
851 if (stream == NULL)
852 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 if (write_mode)
855 mode = "w";
856 else
857 mode = "r";
858 text = PyUnicode_FromString(mode);
859 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
860 goto error;
861 Py_CLEAR(text);
862 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000863
864error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 Py_XDECREF(buf);
866 Py_XDECREF(stream);
867 Py_XDECREF(text);
868 Py_XDECREF(raw);
869 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000870}
871
Georg Brandl1a3284e2007-12-02 09:40:06 +0000872/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000873static int
874initstdio(void)
875{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 PyObject *iomod = NULL, *wrapper;
877 PyObject *bimod = NULL;
878 PyObject *m;
879 PyObject *std = NULL;
880 int status = 0, fd;
881 PyObject * encoding_attr;
882 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 /* Hack to avoid a nasty recursion issue when Python is invoked
885 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
886 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
887 goto error;
888 }
889 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
892 goto error;
893 }
894 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 if (!(bimod = PyImport_ImportModule("builtins"))) {
897 goto error;
898 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 if (!(iomod = PyImport_ImportModule("io"))) {
901 goto error;
902 }
903 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
904 goto error;
905 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* Set builtins.open */
908 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000909 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 goto error;
911 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000912 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 encoding = Py_GETENV("PYTHONIOENCODING");
915 errors = NULL;
916 if (encoding) {
917 encoding = strdup(encoding);
918 errors = strchr(encoding, ':');
919 if (errors) {
920 *errors = '\0';
921 errors++;
922 }
923 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 /* Set sys.stdin */
926 fd = fileno(stdin);
927 /* Under some conditions stdin, stdout and stderr may not be connected
928 * and fileno() may point to an invalid file descriptor. For example
929 * GUI apps don't have valid standard streams by default.
930 */
931 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000932#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 std = Py_None;
934 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000935#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000937#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 }
939 else {
940 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
941 if (std == NULL)
942 goto error;
943 } /* if (fd < 0) */
944 PySys_SetObject("__stdin__", std);
945 PySys_SetObject("stdin", std);
946 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* Set sys.stdout */
949 fd = fileno(stdout);
950 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000951#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 std = Py_None;
953 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000954#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000956#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 }
958 else {
959 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
960 if (std == NULL)
961 goto error;
962 } /* if (fd < 0) */
963 PySys_SetObject("__stdout__", std);
964 PySys_SetObject("stdout", std);
965 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000966
Guido van Rossum98297ee2007-11-06 21:34:58 +0000967#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* Set sys.stderr, replaces the preliminary stderr */
969 fd = fileno(stderr);
970 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000971#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 std = Py_None;
973 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000974#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000976#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 }
978 else {
979 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
980 if (std == NULL)
981 goto error;
982 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 /* Same as hack above, pre-import stderr's codec to avoid recursion
985 when import.c tries to write to stderr in verbose mode. */
986 encoding_attr = PyObject_GetAttrString(std, "encoding");
987 if (encoding_attr != NULL) {
988 const char * encoding;
989 encoding = _PyUnicode_AsString(encoding_attr);
990 if (encoding != NULL) {
991 _PyCodec_Lookup(encoding);
992 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000993 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 }
995 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PySys_SetObject("__stderr__", std);
998 PySys_SetObject("stderr", std);
999 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001000#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001003 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 status = -1;
1005 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (encoding)
1008 free(encoding);
1009 Py_XDECREF(bimod);
1010 Py_XDECREF(iomod);
1011 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001012}
1013
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001014/* Parse input from a file and execute it */
1015
1016int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001017PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 if (filename == NULL)
1021 filename = "???";
1022 if (Py_FdIsInteractive(fp, filename)) {
1023 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1024 if (closeit)
1025 fclose(fp);
1026 return err;
1027 }
1028 else
1029 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001030}
1031
1032int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001033PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyObject *v;
1036 int ret;
1037 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 if (flags == NULL) {
1040 flags = &local_flags;
1041 local_flags.cf_flags = 0;
1042 }
1043 v = PySys_GetObject("ps1");
1044 if (v == NULL) {
1045 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1046 Py_XDECREF(v);
1047 }
1048 v = PySys_GetObject("ps2");
1049 if (v == NULL) {
1050 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1051 Py_XDECREF(v);
1052 }
1053 for (;;) {
1054 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1055 PRINT_TOTAL_REFS();
1056 if (ret == E_EOF)
1057 return 0;
1058 /*
1059 if (ret == E_NOMEM)
1060 return -1;
1061 */
1062 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001063}
1064
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001065/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001066static int PARSER_FLAGS(PyCompilerFlags *flags)
1067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 int parser_flags = 0;
1069 if (!flags)
1070 return 0;
1071 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1072 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1073 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1074 parser_flags |= PyPARSE_IGNORE_COOKIE;
1075 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1076 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1077 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001078}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001079
Thomas Wouters89f507f2006-12-13 04:49:30 +00001080#if 0
1081/* Keep an example of flags with future keyword support. */
1082#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1084 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1085 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1086 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001087#endif
1088
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001089int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001090PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyObject *m, *d, *v, *w, *oenc = NULL;
1093 mod_ty mod;
1094 PyArena *arena;
1095 char *ps1 = "", *ps2 = "", *enc = NULL;
1096 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (fp == stdin) {
1099 /* Fetch encoding from sys.stdin */
1100 v = PySys_GetObject("stdin");
1101 if (v == NULL || v == Py_None)
1102 return -1;
1103 oenc = PyObject_GetAttrString(v, "encoding");
1104 if (!oenc)
1105 return -1;
1106 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001107 if (enc == NULL)
1108 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 }
1110 v = PySys_GetObject("ps1");
1111 if (v != NULL) {
1112 v = PyObject_Str(v);
1113 if (v == NULL)
1114 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001115 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001117 if (ps1 == NULL) {
1118 PyErr_Clear();
1119 ps1 = "";
1120 }
1121 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 }
1123 w = PySys_GetObject("ps2");
1124 if (w != NULL) {
1125 w = PyObject_Str(w);
1126 if (w == NULL)
1127 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001128 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001130 if (ps2 == NULL) {
1131 PyErr_Clear();
1132 ps2 = "";
1133 }
1134 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 }
1136 arena = PyArena_New();
1137 if (arena == NULL) {
1138 Py_XDECREF(v);
1139 Py_XDECREF(w);
1140 Py_XDECREF(oenc);
1141 return -1;
1142 }
1143 mod = PyParser_ASTFromFile(fp, filename, enc,
1144 Py_single_input, ps1, ps2,
1145 flags, &errcode, arena);
1146 Py_XDECREF(v);
1147 Py_XDECREF(w);
1148 Py_XDECREF(oenc);
1149 if (mod == NULL) {
1150 PyArena_Free(arena);
1151 if (errcode == E_EOF) {
1152 PyErr_Clear();
1153 return E_EOF;
1154 }
1155 PyErr_Print();
1156 return -1;
1157 }
1158 m = PyImport_AddModule("__main__");
1159 if (m == NULL) {
1160 PyArena_Free(arena);
1161 return -1;
1162 }
1163 d = PyModule_GetDict(m);
1164 v = run_mod(mod, filename, d, d, flags, arena);
1165 PyArena_Free(arena);
1166 flush_io();
1167 if (v == NULL) {
1168 PyErr_Print();
1169 return -1;
1170 }
1171 Py_DECREF(v);
1172 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001173}
1174
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001175/* Check whether a file maybe a pyc file: Look at the extension,
1176 the file type, and, if we may close it, at the first few bytes. */
1177
1178static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001179maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1182 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 /* Only look into the file if we are allowed to close it, since
1185 it then should also be seekable. */
1186 if (closeit) {
1187 /* Read only two bytes of the magic. If the file was opened in
1188 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1189 be read as they are on disk. */
1190 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1191 unsigned char buf[2];
1192 /* Mess: In case of -x, the stream is NOT at its start now,
1193 and ungetc() was used to push back the first newline,
1194 which makes the current stream position formally undefined,
1195 and a x-platform nightmare.
1196 Unfortunately, we have no direct way to know whether -x
1197 was specified. So we use a terrible hack: if the current
1198 stream position is not 0, we assume -x was specified, and
1199 give up. Bug 132850 on SourceForge spells out the
1200 hopelessness of trying anything else (fseek and ftell
1201 don't work predictably x-platform for text-mode files).
1202 */
1203 int ispyc = 0;
1204 if (ftell(fp) == 0) {
1205 if (fread(buf, 1, 2, fp) == 2 &&
1206 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1207 ispyc = 1;
1208 rewind(fp);
1209 }
1210 return ispyc;
1211 }
1212 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001213}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001214
Guido van Rossum0df002c2000-08-27 19:21:52 +00001215int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001216PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 PyObject *m, *d, *v;
1220 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001221 int set_file_name = 0, ret;
1222 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 m = PyImport_AddModule("__main__");
1225 if (m == NULL)
1226 return -1;
1227 d = PyModule_GetDict(m);
1228 if (PyDict_GetItemString(d, "__file__") == NULL) {
1229 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001230 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (f == NULL)
1232 return -1;
1233 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1234 Py_DECREF(f);
1235 return -1;
1236 }
1237 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1238 return -1;
1239 set_file_name = 1;
1240 Py_DECREF(f);
1241 }
1242 len = strlen(filename);
1243 ext = filename + len - (len > 4 ? 4 : 0);
1244 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1245 /* Try to run a pyc file. First, re-open in binary */
1246 if (closeit)
1247 fclose(fp);
1248 if ((fp = fopen(filename, "rb")) == NULL) {
1249 fprintf(stderr, "python: Can't reopen .pyc file\n");
1250 ret = -1;
1251 goto done;
1252 }
1253 /* Turn on optimization if a .pyo file is given */
1254 if (strcmp(ext, ".pyo") == 0)
1255 Py_OptimizeFlag = 1;
1256 v = run_pyc_file(fp, filename, d, d, flags);
1257 } else {
1258 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1259 closeit, flags);
1260 }
1261 flush_io();
1262 if (v == NULL) {
1263 PyErr_Print();
1264 ret = -1;
1265 goto done;
1266 }
1267 Py_DECREF(v);
1268 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001269 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1271 PyErr_Clear();
1272 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001273}
1274
1275int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001276PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 PyObject *m, *d, *v;
1279 m = PyImport_AddModule("__main__");
1280 if (m == NULL)
1281 return -1;
1282 d = PyModule_GetDict(m);
1283 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1284 if (v == NULL) {
1285 PyErr_Print();
1286 return -1;
1287 }
1288 Py_DECREF(v);
1289 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001290}
1291
Barry Warsaw035574d1997-08-29 22:07:17 +00001292static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001293parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 long hold;
1297 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 /* old style errors */
1300 if (PyTuple_Check(err))
1301 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1302 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (! (v = PyObject_GetAttrString(err, "msg")))
1307 goto finally;
1308 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (!(v = PyObject_GetAttrString(err, "filename")))
1311 goto finally;
1312 if (v == Py_None)
1313 *filename = NULL;
1314 else if (! (*filename = _PyUnicode_AsString(v)))
1315 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 Py_DECREF(v);
1318 if (!(v = PyObject_GetAttrString(err, "lineno")))
1319 goto finally;
1320 hold = PyLong_AsLong(v);
1321 Py_DECREF(v);
1322 v = NULL;
1323 if (hold < 0 && PyErr_Occurred())
1324 goto finally;
1325 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (!(v = PyObject_GetAttrString(err, "offset")))
1328 goto finally;
1329 if (v == Py_None) {
1330 *offset = -1;
1331 Py_DECREF(v);
1332 v = NULL;
1333 } else {
1334 hold = PyLong_AsLong(v);
1335 Py_DECREF(v);
1336 v = NULL;
1337 if (hold < 0 && PyErr_Occurred())
1338 goto finally;
1339 *offset = (int)hold;
1340 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 if (!(v = PyObject_GetAttrString(err, "text")))
1343 goto finally;
1344 if (v == Py_None)
1345 *text = NULL;
1346 else if (!PyUnicode_Check(v) ||
1347 !(*text = _PyUnicode_AsString(v)))
1348 goto finally;
1349 Py_DECREF(v);
1350 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001351
1352finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 Py_XDECREF(v);
1354 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001355}
1356
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001357void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001358PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001361}
1362
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001363static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001364print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 char *nl;
1367 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001368 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1369 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 for (;;) {
1371 nl = strchr(text, '\n');
1372 if (nl == NULL || nl-text >= offset)
1373 break;
1374 offset -= (int)(nl+1-text);
1375 text = nl+1;
1376 }
1377 while (*text == ' ' || *text == '\t') {
1378 text++;
1379 offset--;
1380 }
1381 }
1382 PyFile_WriteString(" ", f);
1383 PyFile_WriteString(text, f);
1384 if (*text == '\0' || text[strlen(text)-1] != '\n')
1385 PyFile_WriteString("\n", f);
1386 if (offset == -1)
1387 return;
1388 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001389 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001392}
1393
Guido van Rossum66e8e862001-03-23 17:54:43 +00001394static void
1395handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 PyObject *exception, *value, *tb;
1398 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 if (Py_InspectFlag)
1401 /* Don't exit if -i flag was given. This flag is set to 0
1402 * when entering interactive mode for inspecting. */
1403 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 PyErr_Fetch(&exception, &value, &tb);
1406 fflush(stdout);
1407 if (value == NULL || value == Py_None)
1408 goto done;
1409 if (PyExceptionInstance_Check(value)) {
1410 /* The error code should be in the `code' attribute. */
1411 PyObject *code = PyObject_GetAttrString(value, "code");
1412 if (code) {
1413 Py_DECREF(value);
1414 value = code;
1415 if (value == Py_None)
1416 goto done;
1417 }
1418 /* If we failed to dig out the 'code' attribute,
1419 just let the else clause below print the error. */
1420 }
1421 if (PyLong_Check(value))
1422 exitcode = (int)PyLong_AsLong(value);
1423 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001424 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001425 if (sys_stderr != NULL && sys_stderr != Py_None) {
1426 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1427 } else {
1428 PyObject_Print(value, stderr, Py_PRINT_RAW);
1429 fflush(stderr);
1430 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PySys_WriteStderr("\n");
1432 exitcode = 1;
1433 }
Tim Peterscf615b52003-04-19 18:47:02 +00001434 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 /* Restore and clear the exception info, in order to properly decref
1436 * the exception, value, and traceback. If we just exit instead,
1437 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1438 * some finalizers from running.
1439 */
1440 PyErr_Restore(exception, value, tb);
1441 PyErr_Clear();
1442 Py_Exit(exitcode);
1443 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001444}
1445
1446void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001447PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1452 handle_system_exit();
1453 }
1454 PyErr_Fetch(&exception, &v, &tb);
1455 if (exception == NULL)
1456 return;
1457 PyErr_NormalizeException(&exception, &v, &tb);
1458 if (tb == NULL) {
1459 tb = Py_None;
1460 Py_INCREF(tb);
1461 }
1462 PyException_SetTraceback(v, tb);
1463 if (exception == NULL)
1464 return;
1465 /* Now we know v != NULL too */
1466 if (set_sys_last_vars) {
1467 PySys_SetObject("last_type", exception);
1468 PySys_SetObject("last_value", v);
1469 PySys_SetObject("last_traceback", tb);
1470 }
1471 hook = PySys_GetObject("excepthook");
1472 if (hook) {
1473 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1474 PyObject *result = PyEval_CallObject(hook, args);
1475 if (result == NULL) {
1476 PyObject *exception2, *v2, *tb2;
1477 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1478 handle_system_exit();
1479 }
1480 PyErr_Fetch(&exception2, &v2, &tb2);
1481 PyErr_NormalizeException(&exception2, &v2, &tb2);
1482 /* It should not be possible for exception2 or v2
1483 to be NULL. However PyErr_Display() can't
1484 tolerate NULLs, so just be safe. */
1485 if (exception2 == NULL) {
1486 exception2 = Py_None;
1487 Py_INCREF(exception2);
1488 }
1489 if (v2 == NULL) {
1490 v2 = Py_None;
1491 Py_INCREF(v2);
1492 }
1493 fflush(stdout);
1494 PySys_WriteStderr("Error in sys.excepthook:\n");
1495 PyErr_Display(exception2, v2, tb2);
1496 PySys_WriteStderr("\nOriginal exception was:\n");
1497 PyErr_Display(exception, v, tb);
1498 Py_DECREF(exception2);
1499 Py_DECREF(v2);
1500 Py_XDECREF(tb2);
1501 }
1502 Py_XDECREF(result);
1503 Py_XDECREF(args);
1504 } else {
1505 PySys_WriteStderr("sys.excepthook is missing\n");
1506 PyErr_Display(exception, v, tb);
1507 }
1508 Py_XDECREF(exception);
1509 Py_XDECREF(v);
1510 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001511}
1512
Benjamin Petersone6528212008-07-15 15:32:09 +00001513static void
1514print_exception(PyObject *f, PyObject *value)
1515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 int err = 0;
1517 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 if (!PyExceptionInstance_Check(value)) {
1520 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1521 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1522 PyFile_WriteString(" found\n", f);
1523 return;
1524 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 Py_INCREF(value);
1527 fflush(stdout);
1528 type = (PyObject *) Py_TYPE(value);
1529 tb = PyException_GetTraceback(value);
1530 if (tb && tb != Py_None)
1531 err = PyTraceBack_Print(tb, f);
1532 if (err == 0 &&
1533 PyObject_HasAttrString(value, "print_file_and_line"))
1534 {
1535 PyObject *message;
1536 const char *filename, *text;
1537 int lineno, offset;
1538 if (!parse_syntax_error(value, &message, &filename,
1539 &lineno, &offset, &text))
1540 PyErr_Clear();
1541 else {
1542 char buf[10];
1543 PyFile_WriteString(" File \"", f);
1544 if (filename == NULL)
1545 PyFile_WriteString("<string>", f);
1546 else
1547 PyFile_WriteString(filename, f);
1548 PyFile_WriteString("\", line ", f);
1549 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1550 PyFile_WriteString(buf, f);
1551 PyFile_WriteString("\n", f);
1552 if (text != NULL)
1553 print_error_text(f, offset, text);
1554 Py_DECREF(value);
1555 value = message;
1556 /* Can't be bothered to check all those
1557 PyFile_WriteString() calls */
1558 if (PyErr_Occurred())
1559 err = -1;
1560 }
1561 }
1562 if (err) {
1563 /* Don't do anything else */
1564 }
1565 else {
1566 PyObject* moduleName;
1567 char* className;
1568 assert(PyExceptionClass_Check(type));
1569 className = PyExceptionClass_Name(type);
1570 if (className != NULL) {
1571 char *dot = strrchr(className, '.');
1572 if (dot != NULL)
1573 className = dot+1;
1574 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 moduleName = PyObject_GetAttrString(type, "__module__");
1577 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1578 {
1579 Py_DECREF(moduleName);
1580 err = PyFile_WriteString("<unknown>", f);
1581 }
1582 else {
1583 char* modstr = _PyUnicode_AsString(moduleName);
1584 if (modstr && strcmp(modstr, "builtins"))
1585 {
1586 err = PyFile_WriteString(modstr, f);
1587 err += PyFile_WriteString(".", f);
1588 }
1589 Py_DECREF(moduleName);
1590 }
1591 if (err == 0) {
1592 if (className == NULL)
1593 err = PyFile_WriteString("<unknown>", f);
1594 else
1595 err = PyFile_WriteString(className, f);
1596 }
1597 }
1598 if (err == 0 && (value != Py_None)) {
1599 PyObject *s = PyObject_Str(value);
1600 /* only print colon if the str() of the
1601 object is not the empty string
1602 */
1603 if (s == NULL)
1604 err = -1;
1605 else if (!PyUnicode_Check(s) ||
1606 PyUnicode_GetSize(s) != 0)
1607 err = PyFile_WriteString(": ", f);
1608 if (err == 0)
1609 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1610 Py_XDECREF(s);
1611 }
1612 /* try to write a newline in any case */
1613 err += PyFile_WriteString("\n", f);
1614 Py_XDECREF(tb);
1615 Py_DECREF(value);
1616 /* If an error happened here, don't show it.
1617 XXX This is wrong, but too many callers rely on this behavior. */
1618 if (err != 0)
1619 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001620}
1621
1622static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 "\nThe above exception was the direct cause "
1624 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001625
1626static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 "\nDuring handling of the above exception, "
1628 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001629
1630static void
1631print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1632{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 int err = 0, res;
1634 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (seen != NULL) {
1637 /* Exception chaining */
1638 if (PySet_Add(seen, value) == -1)
1639 PyErr_Clear();
1640 else if (PyExceptionInstance_Check(value)) {
1641 cause = PyException_GetCause(value);
1642 context = PyException_GetContext(value);
1643 if (cause) {
1644 res = PySet_Contains(seen, cause);
1645 if (res == -1)
1646 PyErr_Clear();
1647 if (res == 0) {
1648 print_exception_recursive(
1649 f, cause, seen);
1650 err |= PyFile_WriteString(
1651 cause_message, f);
1652 }
1653 }
1654 else if (context) {
1655 res = PySet_Contains(seen, context);
1656 if (res == -1)
1657 PyErr_Clear();
1658 if (res == 0) {
1659 print_exception_recursive(
1660 f, context, seen);
1661 err |= PyFile_WriteString(
1662 context_message, f);
1663 }
1664 }
1665 Py_XDECREF(context);
1666 Py_XDECREF(cause);
1667 }
1668 }
1669 print_exception(f, value);
1670 if (err != 0)
1671 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001672}
1673
Thomas Wouters477c8d52006-05-27 19:21:47 +00001674void
1675PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 PyObject *seen;
1678 PyObject *f = PySys_GetObject("stderr");
1679 if (f == Py_None) {
1680 /* pass */
1681 }
1682 else if (f == NULL) {
1683 _PyObject_Dump(value);
1684 fprintf(stderr, "lost sys.stderr\n");
1685 }
1686 else {
1687 /* We choose to ignore seen being possibly NULL, and report
1688 at least the main exception (it could be a MemoryError).
1689 */
1690 seen = PySet_New(NULL);
1691 if (seen == NULL)
1692 PyErr_Clear();
1693 print_exception_recursive(f, value, seen);
1694 Py_XDECREF(seen);
1695 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001696}
1697
Guido van Rossum82598051997-03-05 00:20:32 +00001698PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001699PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 PyObject *ret = NULL;
1703 mod_ty mod;
1704 PyArena *arena = PyArena_New();
1705 if (arena == NULL)
1706 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1709 if (mod != NULL)
1710 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1711 PyArena_Free(arena);
1712 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001713}
1714
1715PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001716PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyObject *ret;
1720 mod_ty mod;
1721 PyArena *arena = PyArena_New();
1722 if (arena == NULL)
1723 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1726 flags, NULL, arena);
1727 if (closeit)
1728 fclose(fp);
1729 if (mod == NULL) {
1730 PyArena_Free(arena);
1731 return NULL;
1732 }
1733 ret = run_mod(mod, filename, globals, locals, flags, arena);
1734 PyArena_Free(arena);
1735 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001736}
1737
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001738static void
1739flush_io(void)
1740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 PyObject *f, *r;
1742 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 /* Save the current exception */
1745 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 f = PySys_GetObject("stderr");
1748 if (f != NULL) {
1749 r = PyObject_CallMethod(f, "flush", "");
1750 if (r)
1751 Py_DECREF(r);
1752 else
1753 PyErr_Clear();
1754 }
1755 f = PySys_GetObject("stdout");
1756 if (f != NULL) {
1757 r = PyObject_CallMethod(f, "flush", "");
1758 if (r)
1759 Py_DECREF(r);
1760 else
1761 PyErr_Clear();
1762 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001765}
1766
Guido van Rossum82598051997-03-05 00:20:32 +00001767static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyCodeObject *co;
1772 PyObject *v;
1773 co = PyAST_Compile(mod, filename, flags, arena);
1774 if (co == NULL)
1775 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001776 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 Py_DECREF(co);
1778 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001779}
1780
Guido van Rossum82598051997-03-05 00:20:32 +00001781static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001782run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 PyCodeObject *co;
1786 PyObject *v;
1787 long magic;
1788 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 magic = PyMarshal_ReadLongFromFile(fp);
1791 if (magic != PyImport_GetMagicNumber()) {
1792 PyErr_SetString(PyExc_RuntimeError,
1793 "Bad magic number in .pyc file");
1794 return NULL;
1795 }
1796 (void) PyMarshal_ReadLongFromFile(fp);
1797 v = PyMarshal_ReadLastObjectFromFile(fp);
1798 fclose(fp);
1799 if (v == NULL || !PyCode_Check(v)) {
1800 Py_XDECREF(v);
1801 PyErr_SetString(PyExc_RuntimeError,
1802 "Bad code object in .pyc file");
1803 return NULL;
1804 }
1805 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001806 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (v && flags)
1808 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1809 Py_DECREF(co);
1810 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001811}
1812
Guido van Rossum82598051997-03-05 00:20:32 +00001813PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001814Py_CompileStringExFlags(const char *str, const char *filename, int start,
1815 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001816{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 PyCodeObject *co;
1818 mod_ty mod;
1819 PyArena *arena = PyArena_New();
1820 if (arena == NULL)
1821 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1824 if (mod == NULL) {
1825 PyArena_Free(arena);
1826 return NULL;
1827 }
1828 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1829 PyObject *result = PyAST_mod2obj(mod);
1830 PyArena_Free(arena);
1831 return result;
1832 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001833 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 PyArena_Free(arena);
1835 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001836}
1837
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001838/* For use in Py_LIMITED_API */
1839#undef Py_CompileString
1840PyObject *
1841PyCompileString(const char *str, const char *filename, int start)
1842{
1843 return Py_CompileStringFlags(str, filename, start, NULL);
1844}
1845
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001846struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001847Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 struct symtable *st;
1850 mod_ty mod;
1851 PyCompilerFlags flags;
1852 PyArena *arena = PyArena_New();
1853 if (arena == NULL)
1854 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 flags.cf_flags = 0;
1857 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1858 if (mod == NULL) {
1859 PyArena_Free(arena);
1860 return NULL;
1861 }
1862 st = PySymtable_Build(mod, filename, 0);
1863 PyArena_Free(arena);
1864 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001865}
1866
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001867/* Preferred access to parser is through AST. */
1868mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001869PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 mod_ty mod;
1873 PyCompilerFlags localflags;
1874 perrdetail err;
1875 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1878 &_PyParser_Grammar, start, &err,
1879 &iflags);
1880 if (flags == NULL) {
1881 localflags.cf_flags = 0;
1882 flags = &localflags;
1883 }
1884 if (n) {
1885 flags->cf_flags |= iflags & PyCF_MASK;
1886 mod = PyAST_FromNode(n, flags, filename, arena);
1887 PyNode_Free(n);
1888 return mod;
1889 }
1890 else {
1891 err_input(&err);
1892 return NULL;
1893 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894}
1895
1896mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001897PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 int start, char *ps1,
1899 char *ps2, PyCompilerFlags *flags, int *errcode,
1900 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 mod_ty mod;
1903 PyCompilerFlags localflags;
1904 perrdetail err;
1905 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1908 &_PyParser_Grammar,
1909 start, ps1, ps2, &err, &iflags);
1910 if (flags == NULL) {
1911 localflags.cf_flags = 0;
1912 flags = &localflags;
1913 }
1914 if (n) {
1915 flags->cf_flags |= iflags & PyCF_MASK;
1916 mod = PyAST_FromNode(n, flags, filename, arena);
1917 PyNode_Free(n);
1918 return mod;
1919 }
1920 else {
1921 err_input(&err);
1922 if (errcode)
1923 *errcode = err.error;
1924 return NULL;
1925 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001926}
1927
Guido van Rossuma110aa61994-08-29 12:50:44 +00001928/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001929
Guido van Rossuma110aa61994-08-29 12:50:44 +00001930node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001931PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 perrdetail err;
1934 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1935 &_PyParser_Grammar,
1936 start, NULL, NULL, &err, flags);
1937 if (n == NULL)
1938 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001941}
1942
Guido van Rossuma110aa61994-08-29 12:50:44 +00001943/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001944
Guido van Rossuma110aa61994-08-29 12:50:44 +00001945node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001946PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 perrdetail err;
1949 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1950 start, &err, flags);
1951 if (n == NULL)
1952 err_input(&err);
1953 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001954}
1955
1956node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001957PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 perrdetail err;
1961 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1962 &_PyParser_Grammar, start, &err, flags);
1963 if (n == NULL)
1964 err_input(&err);
1965 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001966}
1967
1968node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001969PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001972}
1973
Guido van Rossum66ebd912003-04-17 16:02:26 +00001974/* May want to move a more generalized form of this to parsetok.c or
1975 even parser modules. */
1976
1977void
1978PyParser_SetError(perrdetail *err)
1979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001981}
1982
Guido van Rossuma110aa61994-08-29 12:50:44 +00001983/* Set the error appropriate to the given input error code (see errcode.h) */
1984
1985static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001986err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 PyObject *v, *w, *errtype, *errtext;
1989 PyObject *msg_obj = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001990 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 errtype = PyExc_SyntaxError;
1994 switch (err->error) {
1995 case E_ERROR:
1996 return;
1997 case E_SYNTAX:
1998 errtype = PyExc_IndentationError;
1999 if (err->expected == INDENT)
2000 msg = "expected an indented block";
2001 else if (err->token == INDENT)
2002 msg = "unexpected indent";
2003 else if (err->token == DEDENT)
2004 msg = "unexpected unindent";
2005 else {
2006 errtype = PyExc_SyntaxError;
2007 msg = "invalid syntax";
2008 }
2009 break;
2010 case E_TOKEN:
2011 msg = "invalid token";
2012 break;
2013 case E_EOFS:
2014 msg = "EOF while scanning triple-quoted string literal";
2015 break;
2016 case E_EOLS:
2017 msg = "EOL while scanning string literal";
2018 break;
2019 case E_INTR:
2020 if (!PyErr_Occurred())
2021 PyErr_SetNone(PyExc_KeyboardInterrupt);
2022 goto cleanup;
2023 case E_NOMEM:
2024 PyErr_NoMemory();
2025 goto cleanup;
2026 case E_EOF:
2027 msg = "unexpected EOF while parsing";
2028 break;
2029 case E_TABSPACE:
2030 errtype = PyExc_TabError;
2031 msg = "inconsistent use of tabs and spaces in indentation";
2032 break;
2033 case E_OVERFLOW:
2034 msg = "expression too long";
2035 break;
2036 case E_DEDENT:
2037 errtype = PyExc_IndentationError;
2038 msg = "unindent does not match any outer indentation level";
2039 break;
2040 case E_TOODEEP:
2041 errtype = PyExc_IndentationError;
2042 msg = "too many levels of indentation";
2043 break;
2044 case E_DECODE: {
2045 PyObject *type, *value, *tb;
2046 PyErr_Fetch(&type, &value, &tb);
2047 msg = "unknown decode error";
2048 if (value != NULL)
2049 msg_obj = PyObject_Str(value);
2050 Py_XDECREF(type);
2051 Py_XDECREF(value);
2052 Py_XDECREF(tb);
2053 break;
2054 }
2055 case E_LINECONT:
2056 msg = "unexpected character after line continuation character";
2057 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 case E_IDENTIFIER:
2060 msg = "invalid character in identifier";
2061 break;
2062 default:
2063 fprintf(stderr, "error=%d\n", err->error);
2064 msg = "unknown parsing error";
2065 break;
2066 }
2067 /* err->text may not be UTF-8 in case of decoding errors.
2068 Explicitly convert to an object. */
2069 if (!err->text) {
2070 errtext = Py_None;
2071 Py_INCREF(Py_None);
2072 } else {
2073 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2074 "replace");
2075 }
Victor Stinner2f2ed1f2010-10-16 13:42:53 +00002076 if (err->filename != NULL)
2077 filename = PyUnicode_DecodeFSDefault(err->filename);
2078 else {
2079 Py_INCREF(Py_None);
2080 filename = Py_None;
2081 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002082 if (filename != NULL)
2083 v = Py_BuildValue("(NiiN)", filename,
2084 err->lineno, err->offset, errtext);
2085 else
2086 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 if (v != NULL) {
2088 if (msg_obj)
2089 w = Py_BuildValue("(OO)", msg_obj, v);
2090 else
2091 w = Py_BuildValue("(sO)", msg, v);
2092 } else
2093 w = NULL;
2094 Py_XDECREF(v);
2095 PyErr_SetObject(errtype, w);
2096 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002097cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 Py_XDECREF(msg_obj);
2099 if (err->text != NULL) {
2100 PyObject_FREE(err->text);
2101 err->text = NULL;
2102 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002103}
2104
2105/* Print fatal error message and abort */
2106
2107void
Tim Peters7c321a82002-07-09 02:57:01 +00002108Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 fprintf(stderr, "Fatal Python error: %s\n", msg);
2111 fflush(stderr); /* it helps in Windows debug build */
2112 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002113 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002115#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 {
2117 size_t len = strlen(msg);
2118 WCHAR* buffer;
2119 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 /* Convert the message to wchar_t. This uses a simple one-to-one
2122 conversion, assuming that the this error message actually uses ASCII
2123 only. If this ceases to be true, we will have to convert. */
2124 buffer = alloca( (len+1) * (sizeof *buffer));
2125 for( i=0; i<=len; ++i)
2126 buffer[i] = msg[i];
2127 OutputDebugStringW(L"Fatal Python error: ");
2128 OutputDebugStringW(buffer);
2129 OutputDebugStringW(L"\n");
2130 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002131#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002133#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002134#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002136}
2137
2138/* Clean up and exit */
2139
Guido van Rossuma110aa61994-08-29 12:50:44 +00002140#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002141#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002142#endif
2143
Collin Winter670e6922007-03-21 02:57:17 +00002144static void (*pyexitfunc)(void) = NULL;
2145/* For the atexit module. */
2146void _Py_PyAtExit(void (*func)(void))
2147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002149}
2150
2151static void
2152call_py_exitfuncs(void)
2153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 if (pyexitfunc == NULL)
2155 return;
Collin Winter670e6922007-03-21 02:57:17 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 (*pyexitfunc)();
2158 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002159}
2160
Antoine Pitrou011bd622009-10-20 21:52:47 +00002161/* Wait until threading._shutdown completes, provided
2162 the threading module was imported in the first place.
2163 The shutdown routine will wait until all non-daemon
2164 "threading" threads have completed. */
2165static void
2166wait_for_thread_shutdown(void)
2167{
2168#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 PyObject *result;
2170 PyThreadState *tstate = PyThreadState_GET();
2171 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2172 "threading");
2173 if (threading == NULL) {
2174 /* threading not imported */
2175 PyErr_Clear();
2176 return;
2177 }
2178 result = PyObject_CallMethod(threading, "_shutdown", "");
2179 if (result == NULL) {
2180 PyErr_WriteUnraisable(threading);
2181 }
2182 else {
2183 Py_DECREF(result);
2184 }
2185 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002186#endif
2187}
2188
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002189#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002190static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002191static int nexitfuncs = 0;
2192
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002193int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (nexitfuncs >= NEXITFUNCS)
2196 return -1;
2197 exitfuncs[nexitfuncs++] = func;
2198 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002199}
2200
Guido van Rossumcc283f51997-08-05 02:22:03 +00002201static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002202call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 while (nexitfuncs > 0)
2205 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 fflush(stdout);
2208 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002209}
2210
2211void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002212Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002217}
2218
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002219static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002220initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002221{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002222#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002224#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002225#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002227#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002228#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002230#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002232}
2233
Guido van Rossum7433b121997-02-14 19:45:36 +00002234
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002235/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2236 *
2237 * All of the code in this function must only use async-signal-safe functions,
2238 * listed at `man 7 signal` or
2239 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2240 */
2241void
2242_Py_RestoreSignals(void)
2243{
2244#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002246#endif
2247#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002249#endif
2250#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002252#endif
2253}
2254
2255
Guido van Rossum7433b121997-02-14 19:45:36 +00002256/*
2257 * The file descriptor fd is considered ``interactive'' if either
2258 * a) isatty(fd) is TRUE, or
2259 * b) the -i flag was given, and the filename associated with
2260 * the descriptor is NULL or "<stdin>" or "???".
2261 */
2262int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002263Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 if (isatty((int)fileno(fp)))
2266 return 1;
2267 if (!Py_InteractiveFlag)
2268 return 0;
2269 return (filename == NULL) ||
2270 (strcmp(filename, "<stdin>") == 0) ||
2271 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002272}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002273
2274
Tim Petersd08e3822003-04-17 15:24:21 +00002275#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002276#if defined(WIN32) && defined(_MSC_VER)
2277
2278/* Stack checking for Microsoft C */
2279
2280#include <malloc.h>
2281#include <excpt.h>
2282
Fred Drakee8de31c2000-08-31 05:38:39 +00002283/*
2284 * Return non-zero when we run out of memory on the stack; zero otherwise.
2285 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002286int
Fred Drake399739f2000-08-31 05:52:44 +00002287PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 __try {
2290 /* alloca throws a stack overflow exception if there's
2291 not enough space left on the stack */
2292 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2293 return 0;
2294 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2295 EXCEPTION_EXECUTE_HANDLER :
2296 EXCEPTION_CONTINUE_SEARCH) {
2297 int errcode = _resetstkoflw();
2298 if (errcode == 0)
2299 {
2300 Py_FatalError("Could not reset the stack!");
2301 }
2302 }
2303 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002304}
2305
2306#endif /* WIN32 && _MSC_VER */
2307
2308/* Alternate implementations can be added here... */
2309
2310#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002311
2312
2313/* Wrappers around sigaction() or signal(). */
2314
2315PyOS_sighandler_t
2316PyOS_getsig(int sig)
2317{
2318#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 struct sigaction context;
2320 if (sigaction(sig, NULL, &context) == -1)
2321 return SIG_ERR;
2322 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002323#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002325/* Special signal handling for the secure CRT in Visual Studio 2005 */
2326#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 switch (sig) {
2328 /* Only these signals are valid */
2329 case SIGINT:
2330 case SIGILL:
2331 case SIGFPE:
2332 case SIGSEGV:
2333 case SIGTERM:
2334 case SIGBREAK:
2335 case SIGABRT:
2336 break;
2337 /* Don't call signal() with other values or it will assert */
2338 default:
2339 return SIG_ERR;
2340 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002341#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 handler = signal(sig, SIG_IGN);
2343 if (handler != SIG_ERR)
2344 signal(sig, handler);
2345 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002346#endif
2347}
2348
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002349/*
2350 * All of the code in this function must only use async-signal-safe functions,
2351 * listed at `man 7 signal` or
2352 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2353 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002354PyOS_sighandler_t
2355PyOS_setsig(int sig, PyOS_sighandler_t handler)
2356{
2357#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 /* Some code in Modules/signalmodule.c depends on sigaction() being
2359 * used here if HAVE_SIGACTION is defined. Fix that if this code
2360 * changes to invalidate that assumption.
2361 */
2362 struct sigaction context, ocontext;
2363 context.sa_handler = handler;
2364 sigemptyset(&context.sa_mask);
2365 context.sa_flags = 0;
2366 if (sigaction(sig, &context, &ocontext) == -1)
2367 return SIG_ERR;
2368 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002369#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 PyOS_sighandler_t oldhandler;
2371 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002372#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002374#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002376#endif
2377}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002378
2379/* Deprecated C API functions still provided for binary compatiblity */
2380
2381#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002382PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386}
2387
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002388#undef PyParser_SimpleParseString
2389PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390PyParser_SimpleParseString(const char *str, int start)
2391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002393}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002394
2395#undef PyRun_AnyFile
2396PyAPI_FUNC(int)
2397PyRun_AnyFile(FILE *fp, const char *name)
2398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002400}
2401
2402#undef PyRun_AnyFileEx
2403PyAPI_FUNC(int)
2404PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002407}
2408
2409#undef PyRun_AnyFileFlags
2410PyAPI_FUNC(int)
2411PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002414}
2415
2416#undef PyRun_File
2417PyAPI_FUNC(PyObject *)
2418PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002421}
2422
2423#undef PyRun_FileEx
2424PyAPI_FUNC(PyObject *)
2425PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002428}
2429
2430#undef PyRun_FileFlags
2431PyAPI_FUNC(PyObject *)
2432PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002436}
2437
2438#undef PyRun_SimpleFile
2439PyAPI_FUNC(int)
2440PyRun_SimpleFile(FILE *f, const char *p)
2441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002443}
2444
2445#undef PyRun_SimpleFileEx
2446PyAPI_FUNC(int)
2447PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002450}
2451
2452
2453#undef PyRun_String
2454PyAPI_FUNC(PyObject *)
2455PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002458}
2459
2460#undef PyRun_SimpleString
2461PyAPI_FUNC(int)
2462PyRun_SimpleString(const char *s)
2463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002465}
2466
2467#undef Py_CompileString
2468PyAPI_FUNC(PyObject *)
2469Py_CompileString(const char *str, const char *p, int s)
2470{
Georg Brandl8334fd92010-12-04 10:26:46 +00002471 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2472}
2473
2474#undef Py_CompileStringFlags
2475PyAPI_FUNC(PyObject *)
2476Py_CompileStringFlags(const char *str, const char *p, int s,
2477 PyCompilerFlags *flags)
2478{
2479 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002480}
2481
2482#undef PyRun_InteractiveOne
2483PyAPI_FUNC(int)
2484PyRun_InteractiveOne(FILE *f, const char *p)
2485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002487}
2488
2489#undef PyRun_InteractiveLoop
2490PyAPI_FUNC(int)
2491PyRun_InteractiveLoop(FILE *f, const char *p)
2492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002494}
2495
2496#ifdef __cplusplus
2497}
2498#endif