blob: f7335a2b21d3666a244506c00b022c296aebe709 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
43 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#endif
45
46#ifdef __cplusplus
47extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000048#endif
49
Martin v. Löwis790465f2008-04-05 20:41:37 +000050extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000051
Guido van Rossum82598051997-03-05 00:20:32 +000052extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossumb73cc041993-11-01 16:28:59 +000054/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static void initmain(void);
Victor Stinnerb744ba12010-05-15 12:27:16 +000056static void initfsencoding(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
65static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000066static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000067static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000068static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000069extern void _PyUnicode_Init(void);
70extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000071extern int _PyLong_Init(void);
72extern void PyLong_Fini(void);
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 */
Guido van Rossum7433b121997-02-14 19:45:36 +000081int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000082int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000083int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000084int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000085int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000086int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000087int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000088int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000089int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000090int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000091
Christian Heimes33fe8092008-04-13 13:53:33 +000092/* PyModule_GetWarningsModule is no longer necessary as of 2.6
93since _warnings is builtin. This API should not be used. */
94PyObject *
95PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000098}
Mark Hammonda43fd0c2003-02-19 00:33:33 +000099
Guido van Rossum25ce5661997-08-02 03:10:38 +0000100static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000101
Thomas Wouters7e474022000-07-16 12:04:32 +0000102/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000103
104int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000105Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000108}
109
Guido van Rossum25ce5661997-08-02 03:10:38 +0000110/* Global initializations. Can be undone by Py_Finalize(). Don't
111 call this twice without an intervening Py_Finalize() call. When
112 initializations fail, a fatal error is issued and the function does
113 not return. On return, the first thread and interpreter state have
114 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116 Locking: you must hold the interpreter lock while calling this.
117 (If the lock has not yet been initialized, that's equivalent to
118 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000119
Guido van Rossum25ce5661997-08-02 03:10:38 +0000120*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000121
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000122static int
123add_flag(int flag, const char *envs)
124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 int env = atoi(envs);
126 if (flag < env)
127 flag = env;
128 if (flag < 1)
129 flag = 1;
130 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000131}
132
Christian Heimes5833a2f2008-10-30 21:40:04 +0000133static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000134get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000135{
Victor Stinner94908bb2010-08-18 21:23:25 +0000136 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000137 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000138
Victor Stinner94908bb2010-08-18 21:23:25 +0000139 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 if (!codec)
141 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 name = PyObject_GetAttrString(codec, "name");
144 Py_CLEAR(codec);
145 if (!name)
146 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000147
Victor Stinner94908bb2010-08-18 21:23:25 +0000148 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner386fe712010-05-19 00:34:15 +0000149 if (name == NULL)
150 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000151 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000153 if (name_str == NULL) {
154 PyErr_NoMemory();
155 return NULL;
156 }
157 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000158
159error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000161 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000163}
Victor Stinner94908bb2010-08-18 21:23:25 +0000164
165#if defined(HAVE_LANGINFO_H) && defined(CODESET)
166static char*
167get_codeset(void)
168{
169 char* codeset = nl_langinfo(CODESET);
170 if (!codeset || codeset[0] == '\0') {
171 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
172 return NULL;
173 }
174 return get_codec_name(codeset);
175}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000176#endif
177
Guido van Rossuma027efa1997-05-05 20:56:21 +0000178void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000179Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 PyInterpreterState *interp;
182 PyThreadState *tstate;
183 PyObject *bimod, *sysmod, *pstderr;
184 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 if (initialized)
188 return;
189 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000190
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000191#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 /* Set up the LC_CTYPE locale, so we can obtain
193 the locale's charset without having to switch
194 locales. */
195 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000196#endif
197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
199 Py_DebugFlag = add_flag(Py_DebugFlag, p);
200 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
201 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
202 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
203 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
204 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
205 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 interp = PyInterpreterState_New();
208 if (interp == NULL)
209 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 tstate = PyThreadState_New(interp);
212 if (tstate == NULL)
213 Py_FatalError("Py_Initialize: can't make first thread");
214 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000215
Victor Stinner6961bd62010-08-17 22:26:51 +0000216#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000217 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
218 destroying the GIL might fail when it is being referenced from
219 another running thread (see issue #9901).
220 Instead we destroy the previously created GIL here, which ensures
221 that we can call Py_Initialize / Py_Finalize multiple times. */
222 _PyEval_FiniThreads();
223
224 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000225 _PyGILState_Init(interp, tstate);
226#endif /* WITH_THREAD */
227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (!_PyFrame_Init())
231 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (!_PyLong_Init())
234 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (!PyByteArray_Init())
237 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 interp->modules = PyDict_New();
242 if (interp->modules == NULL)
243 Py_FatalError("Py_Initialize: can't make modules dictionary");
244 interp->modules_reloading = PyDict_New();
245 if (interp->modules_reloading == NULL)
246 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 /* Init Unicode implementation; relies on the codec registry */
249 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 bimod = _PyBuiltin_Init();
252 if (bimod == NULL)
253 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000254 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 interp->builtins = PyModule_GetDict(bimod);
256 if (interp->builtins == NULL)
257 Py_FatalError("Py_Initialize: can't initialize builtins dict");
258 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 /* initialize builtin exceptions */
261 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 sysmod = _PySys_Init();
264 if (sysmod == NULL)
265 Py_FatalError("Py_Initialize: can't initialize sys");
266 interp->sysdict = PyModule_GetDict(sysmod);
267 if (interp->sysdict == NULL)
268 Py_FatalError("Py_Initialize: can't initialize sys dict");
269 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000270 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 PySys_SetPath(Py_GetPath());
272 PyDict_SetItemString(interp->sysdict, "modules",
273 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 /* Set up a preliminary stderr printer until we have enough
276 infrastructure for the io module in place. */
277 pstderr = PyFile_NewStdPrinter(fileno(stderr));
278 if (pstderr == NULL)
279 Py_FatalError("Py_Initialize: can't set preliminary stderr");
280 PySys_SetObject("stderr", pstderr);
281 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000282 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000287
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000288 /* Initialize _warnings. */
289 _PyWarnings_Init();
290
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000291 _PyTime_Init();
292
Victor Stinnerb744ba12010-05-15 12:27:16 +0000293 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 if (install_sigs)
296 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 initmain(); /* Module __main__ */
299 if (initstdio() < 0)
300 Py_FatalError(
301 "Py_Initialize: can't initialize sys standard streams");
302
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000303 /* Initialize warnings. */
304 if (PySys_HasWarnOptions()) {
305 PyObject *warnings_module = PyImport_ImportModule("warnings");
306 if (warnings_module == NULL) {
307 fprintf(stderr, "'import warnings' failed; traceback:\n");
308 PyErr_Print();
309 }
310 Py_XDECREF(warnings_module);
311 }
312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 if (!Py_NoSiteFlag)
314 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000315}
316
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000317void
318Py_Initialize(void)
319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000321}
322
323
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000324#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000325extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000326#endif
327
Guido van Rossume8432ac2007-07-09 15:04:50 +0000328/* Flush stdout and stderr */
329
Neal Norwitz2bad9702007-08-27 06:19:22 +0000330static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000331flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *fout = PySys_GetObject("stdout");
334 PyObject *ferr = PySys_GetObject("stderr");
335 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (fout != NULL && fout != Py_None) {
338 tmp = PyObject_CallMethod(fout, "flush", "");
339 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000340 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 else
342 Py_DECREF(tmp);
343 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000344
Victor Stinner9467b212010-05-14 00:59:09 +0000345 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 tmp = PyObject_CallMethod(ferr, "flush", "");
347 if (tmp == NULL)
348 PyErr_Clear();
349 else
350 Py_DECREF(tmp);
351 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000352}
353
Guido van Rossum25ce5661997-08-02 03:10:38 +0000354/* Undo the effect of Py_Initialize().
355
356 Beware: if multiple interpreter and/or thread states exist, these
357 are not wiped out; only the current thread and interpreter state
358 are deleted. But since everything else is deleted, those other
359 interpreter and thread states should no longer be used.
360
361 (XXX We should do better, e.g. wipe out all interpreters and
362 threads.)
363
364 Locking: as above.
365
366*/
367
368void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000369Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyInterpreterState *interp;
372 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (!initialized)
375 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 /* The interpreter is still entirely intact at this point, and the
380 * exit funcs may be relying on that. In particular, if some thread
381 * or exit func is still waiting to do an import, the import machinery
382 * expects Py_IsInitialized() to return true. So don't say the
383 * interpreter is uninitialized until after the exit funcs have run.
384 * Note that Threading.py uses an exit func to do a join on all the
385 * threads created thru it, so this also protects pending imports in
386 * the threads created via Threading.
387 */
388 call_py_exitfuncs();
389 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 /* Flush stdout+stderr */
392 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 /* Get current thread state and interpreter pointer */
395 tstate = PyThreadState_GET();
396 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 /* Disable signal handling */
399 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 /* Clear type lookup cache */
402 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 /* Collect garbage. This may call finalizers; it's nice to call these
405 * before all modules are destroyed.
406 * XXX If a __del__ or weakref callback is triggered here, and tries to
407 * XXX import a module, bad things can happen, because Python no
408 * XXX longer believes it's initialized.
409 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
410 * XXX is easy to provoke that way. I've also seen, e.g.,
411 * XXX Exception exceptions.ImportError: 'No module named sha'
412 * XXX in <function callback at 0x008F5718> ignored
413 * XXX but I'm unclear on exactly how that one happens. In any case,
414 * XXX I haven't seen a real-life report of either of these.
415 */
416 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 /* With COUNT_ALLOCS, it helps to run GC multiple times:
419 each collection might release some types from the type
420 list, so they become garbage. */
421 while (PyGC_Collect() > 0)
422 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000423#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000424 /* We run this while most interpreter state is still alive, so that
425 debug information can be printed out */
426 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 /* Destroy all modules */
429 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 /* Flush stdout+stderr (again, in case more was printed) */
432 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 /* Collect final garbage. This disposes of cycles created by
435 * new-style class definitions, for example.
436 * XXX This is disabled because it caused too many problems. If
437 * XXX a __del__ or weakref callback triggers here, Python code has
438 * XXX a hard time running, because even the sys module has been
439 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
440 * XXX One symptom is a sequence of information-free messages
441 * XXX coming from threads (if a __del__ or callback is invoked,
442 * XXX other threads can execute too, and any exception they encounter
443 * XXX triggers a comedy of errors as subsystem after subsystem
444 * XXX fails to find what it *expects* to find in sys to help report
445 * XXX the exception and consequent unexpected failures). I've also
446 * XXX seen segfaults then, after adding print statements to the
447 * XXX Python code getting called.
448 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000449#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000451#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
454 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000457#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000459#endif
460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000462
Tim Peters9cf25ce2003-04-17 15:21:01 +0000463#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 /* Display all objects still alive -- this can invoke arbitrary
465 * __repr__ overrides, so requires a mostly-intact interpreter.
466 * Alas, a lot of stuff may still be alive now that will be cleaned
467 * up later.
468 */
469 if (Py_GETENV("PYTHONDUMPREFS"))
470 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000471#endif /* Py_TRACE_REFS */
472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 /* Clear interpreter state */
474 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* Now we decref the exception classes. After this point nothing
477 can raise an exception. That's okay, because each Fini() method
478 below has been checked to make sure no exceptions are ever
479 raised.
480 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000485#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000487#endif /* WITH_THREAD */
488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* Delete current thread */
490 PyThreadState_Swap(NULL);
491 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 /* Sundry finalizers */
494 PyMethod_Fini();
495 PyFrame_Fini();
496 PyCFunction_Fini();
497 PyTuple_Fini();
498 PyList_Fini();
499 PySet_Fini();
500 PyBytes_Fini();
501 PyByteArray_Fini();
502 PyLong_Fini();
503 PyFloat_Fini();
504 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 /* Cleanup Unicode implementation */
507 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000510 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 free((char*)Py_FileSystemDefaultEncoding);
512 Py_FileSystemDefaultEncoding = NULL;
513 }
Christian Heimesc8967002007-11-30 10:18:26 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 /* XXX Still allocated:
516 - various static ad-hoc pointers to interned strings
517 - int and float free list blocks
518 - whatever various modules and libraries allocate
519 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000522
Tim Peters269b2a62003-04-17 19:52:29 +0000523#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 /* Display addresses (& refcnts) of all objects still alive.
525 * An address can be used to find the repr of the object, printed
526 * above by _Py_PrintReferences.
527 */
528 if (Py_GETENV("PYTHONDUMPREFS"))
529 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000530#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000531#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (Py_GETENV("PYTHONMALLOCSTATS"))
533 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000534#endif
535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000537}
538
539/* Create and initialize a new interpreter and thread, and return the
540 new thread. This requires that Py_Initialize() has been called
541 first.
542
543 Unsuccessful initialization yields a NULL pointer. Note that *no*
544 exception information is available even in this case -- the
545 exception information is held in the thread, and there is no
546 thread.
547
548 Locking: as above.
549
550*/
551
552PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000553Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 PyInterpreterState *interp;
556 PyThreadState *tstate, *save_tstate;
557 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (!initialized)
560 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 interp = PyInterpreterState_New();
563 if (interp == NULL)
564 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 tstate = PyThreadState_New(interp);
567 if (tstate == NULL) {
568 PyInterpreterState_Delete(interp);
569 return NULL;
570 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 interp->modules = PyDict_New();
577 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000578
Victor Stinner49d3f252010-10-17 01:24:53 +0000579 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (bimod != NULL) {
581 interp->builtins = PyModule_GetDict(bimod);
582 if (interp->builtins == NULL)
583 goto handle_error;
584 Py_INCREF(interp->builtins);
585 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 /* initialize builtin exceptions */
588 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000589
Victor Stinner49d3f252010-10-17 01:24:53 +0000590 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 if (bimod != NULL && sysmod != NULL) {
592 PyObject *pstderr;
593 interp->sysdict = PyModule_GetDict(sysmod);
594 if (interp->sysdict == NULL)
595 goto handle_error;
596 Py_INCREF(interp->sysdict);
597 PySys_SetPath(Py_GetPath());
598 PyDict_SetItemString(interp->sysdict, "modules",
599 interp->modules);
600 /* Set up a preliminary stderr printer until we have enough
601 infrastructure for the io module in place. */
602 pstderr = PyFile_NewStdPrinter(fileno(stderr));
603 if (pstderr == NULL)
604 Py_FatalError("Py_Initialize: can't set preliminary stderr");
605 PySys_SetObject("stderr", pstderr);
606 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000607 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 _PyImportHooks_Init();
610 if (initstdio() < 0)
611 Py_FatalError(
612 "Py_Initialize: can't initialize sys standard streams");
613 initmain();
614 if (!Py_NoSiteFlag)
615 initsite();
616 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (!PyErr_Occurred())
619 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000620
Thomas Wouters89f507f2006-12-13 04:49:30 +0000621handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 PyErr_Print();
625 PyThreadState_Clear(tstate);
626 PyThreadState_Swap(save_tstate);
627 PyThreadState_Delete(tstate);
628 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631}
632
633/* Delete an interpreter and its last thread. This requires that the
634 given thread state is current, that the thread has no remaining
635 frames, and that it is its interpreter's only remaining thread.
636 It is a fatal error to violate these constraints.
637
638 (Py_Finalize() doesn't have these constraints -- it zaps
639 everything, regardless.)
640
641 Locking: as above.
642
643*/
644
645void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000646Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (tstate != PyThreadState_GET())
651 Py_FatalError("Py_EndInterpreter: thread is not current");
652 if (tstate->frame != NULL)
653 Py_FatalError("Py_EndInterpreter: thread still has a frame");
654 if (tstate != interp->tstate_head || tstate->next != NULL)
655 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyImport_Cleanup();
658 PyInterpreterState_Clear(interp);
659 PyThreadState_Swap(NULL);
660 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000661}
662
Martin v. Löwis790465f2008-04-05 20:41:37 +0000663static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000664
665void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000666Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (pn && *pn)
669 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000670}
671
Martin v. Löwis790465f2008-04-05 20:41:37 +0000672wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000673Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000676}
677
Martin v. Löwis790465f2008-04-05 20:41:37 +0000678static wchar_t *default_home = NULL;
679static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000680
681void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000682Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000685}
686
Martin v. Löwis790465f2008-04-05 20:41:37 +0000687wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000688Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 wchar_t *home = default_home;
691 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
692 char* chome = Py_GETENV("PYTHONHOME");
693 if (chome) {
694 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
695 if (r != (size_t)-1 && r <= PATH_MAX)
696 home = env_home;
697 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 }
700 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000701}
702
Guido van Rossum6135a871995-01-09 17:53:26 +0000703/* Create __main__ module */
704
705static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000706initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyObject *m, *d;
709 m = PyImport_AddModule("__main__");
710 if (m == NULL)
711 Py_FatalError("can't create __main__ module");
712 d = PyModule_GetDict(m);
713 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
714 PyObject *bimod = PyImport_ImportModule("builtins");
715 if (bimod == NULL ||
716 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
717 Py_FatalError("can't add __builtins__ to __main__");
718 Py_DECREF(bimod);
719 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000720}
721
Victor Stinnerb744ba12010-05-15 12:27:16 +0000722static void
723initfsencoding(void)
724{
725 PyObject *codec;
726#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000727 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000728
Victor Stinner7f84ab52010-06-11 00:36:33 +0000729 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000730 /* On Unix, set the file system encoding according to the
731 user's preference, if the CODESET names a well-known
732 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000733 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000734 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000735 if (codeset == NULL)
736 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000737
Victor Stinnere4743092010-10-19 00:05:51 +0000738 Py_FileSystemDefaultEncoding = codeset;
739 Py_HasFileSystemDefaultEncoding = 0;
740 return;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000741 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000742#endif
743
744 /* the encoding is mbcs, utf-8 or ascii */
745 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
746 if (!codec) {
747 /* Such error can only occurs in critical situations: no more
748 * memory, import a module of the standard library failed,
749 * etc. */
750 Py_FatalError("Py_Initialize: unable to load the file system codec");
751 } else {
752 Py_DECREF(codec);
753 }
754}
755
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000756/* Import the site module (not into __main__ though) */
757
758static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000759initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyObject *m;
762 m = PyImport_ImportModule("site");
763 if (m == NULL) {
764 PyErr_Print();
765 Py_Finalize();
766 exit(1);
767 }
768 else {
769 Py_DECREF(m);
770 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000771}
772
Antoine Pitrou05608432009-01-09 18:53:14 +0000773static PyObject*
774create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 int fd, int write_mode, char* name,
776 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
779 const char* mode;
780 PyObject *line_buffering;
781 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 /* stdin is always opened in buffered mode, first because it shouldn't
784 make a difference in common use cases, second because TextIOWrapper
785 depends on the presence of a read1() method which only exists on
786 buffered streams.
787 */
788 if (Py_UnbufferedStdioFlag && write_mode)
789 buffering = 0;
790 else
791 buffering = -1;
792 if (write_mode)
793 mode = "wb";
794 else
795 mode = "rb";
796 buf = PyObject_CallMethod(io, "open", "isiOOOi",
797 fd, mode, buffering,
798 Py_None, Py_None, Py_None, 0);
799 if (buf == NULL)
800 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 if (buffering) {
803 raw = PyObject_GetAttrString(buf, "raw");
804 if (raw == NULL)
805 goto error;
806 }
807 else {
808 raw = buf;
809 Py_INCREF(raw);
810 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 text = PyUnicode_FromString(name);
813 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
814 goto error;
815 res = PyObject_CallMethod(raw, "isatty", "");
816 if (res == NULL)
817 goto error;
818 isatty = PyObject_IsTrue(res);
819 Py_DECREF(res);
820 if (isatty == -1)
821 goto error;
822 if (isatty || Py_UnbufferedStdioFlag)
823 line_buffering = Py_True;
824 else
825 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 Py_CLEAR(raw);
828 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
831 buf, encoding, errors,
832 "\n", line_buffering);
833 Py_CLEAR(buf);
834 if (stream == NULL)
835 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (write_mode)
838 mode = "w";
839 else
840 mode = "r";
841 text = PyUnicode_FromString(mode);
842 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
843 goto error;
844 Py_CLEAR(text);
845 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000846
847error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 Py_XDECREF(buf);
849 Py_XDECREF(stream);
850 Py_XDECREF(text);
851 Py_XDECREF(raw);
852 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000853}
854
Georg Brandl1a3284e2007-12-02 09:40:06 +0000855/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000856static int
857initstdio(void)
858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyObject *iomod = NULL, *wrapper;
860 PyObject *bimod = NULL;
861 PyObject *m;
862 PyObject *std = NULL;
863 int status = 0, fd;
864 PyObject * encoding_attr;
865 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 /* Hack to avoid a nasty recursion issue when Python is invoked
868 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
869 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
870 goto error;
871 }
872 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
875 goto error;
876 }
877 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 if (!(bimod = PyImport_ImportModule("builtins"))) {
880 goto error;
881 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 if (!(iomod = PyImport_ImportModule("io"))) {
884 goto error;
885 }
886 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
887 goto error;
888 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 /* Set builtins.open */
891 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000892 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 goto error;
894 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000895 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 encoding = Py_GETENV("PYTHONIOENCODING");
898 errors = NULL;
899 if (encoding) {
900 encoding = strdup(encoding);
901 errors = strchr(encoding, ':');
902 if (errors) {
903 *errors = '\0';
904 errors++;
905 }
906 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 /* Set sys.stdin */
909 fd = fileno(stdin);
910 /* Under some conditions stdin, stdout and stderr may not be connected
911 * and fileno() may point to an invalid file descriptor. For example
912 * GUI apps don't have valid standard streams by default.
913 */
914 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000915#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 std = Py_None;
917 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000918#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000920#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 }
922 else {
923 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
924 if (std == NULL)
925 goto error;
926 } /* if (fd < 0) */
927 PySys_SetObject("__stdin__", std);
928 PySys_SetObject("stdin", std);
929 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* Set sys.stdout */
932 fd = fileno(stdout);
933 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000934#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 std = Py_None;
936 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000937#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000939#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 }
941 else {
942 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
943 if (std == NULL)
944 goto error;
945 } /* if (fd < 0) */
946 PySys_SetObject("__stdout__", std);
947 PySys_SetObject("stdout", std);
948 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000949
Guido van Rossum98297ee2007-11-06 21:34:58 +0000950#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 /* Set sys.stderr, replaces the preliminary stderr */
952 fd = fileno(stderr);
953 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000954#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 std = Py_None;
956 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000957#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000959#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 }
961 else {
962 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
963 if (std == NULL)
964 goto error;
965 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 /* Same as hack above, pre-import stderr's codec to avoid recursion
968 when import.c tries to write to stderr in verbose mode. */
969 encoding_attr = PyObject_GetAttrString(std, "encoding");
970 if (encoding_attr != NULL) {
971 const char * encoding;
972 encoding = _PyUnicode_AsString(encoding_attr);
973 if (encoding != NULL) {
974 _PyCodec_Lookup(encoding);
975 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000976 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 }
978 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PySys_SetObject("__stderr__", std);
981 PySys_SetObject("stderr", std);
982 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000983#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000986 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 status = -1;
988 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (encoding)
991 free(encoding);
992 Py_XDECREF(bimod);
993 Py_XDECREF(iomod);
994 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000995}
996
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000997/* Parse input from a file and execute it */
998
999int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001000PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 if (filename == NULL)
1004 filename = "???";
1005 if (Py_FdIsInteractive(fp, filename)) {
1006 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1007 if (closeit)
1008 fclose(fp);
1009 return err;
1010 }
1011 else
1012 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001013}
1014
1015int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001016PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 PyObject *v;
1019 int ret;
1020 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (flags == NULL) {
1023 flags = &local_flags;
1024 local_flags.cf_flags = 0;
1025 }
1026 v = PySys_GetObject("ps1");
1027 if (v == NULL) {
1028 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1029 Py_XDECREF(v);
1030 }
1031 v = PySys_GetObject("ps2");
1032 if (v == NULL) {
1033 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1034 Py_XDECREF(v);
1035 }
1036 for (;;) {
1037 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1038 PRINT_TOTAL_REFS();
1039 if (ret == E_EOF)
1040 return 0;
1041 /*
1042 if (ret == E_NOMEM)
1043 return -1;
1044 */
1045 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001046}
1047
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001048/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001049static int PARSER_FLAGS(PyCompilerFlags *flags)
1050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 int parser_flags = 0;
1052 if (!flags)
1053 return 0;
1054 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1055 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1056 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1057 parser_flags |= PyPARSE_IGNORE_COOKIE;
1058 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1059 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1060 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001061}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001062
Thomas Wouters89f507f2006-12-13 04:49:30 +00001063#if 0
1064/* Keep an example of flags with future keyword support. */
1065#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1067 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1068 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1069 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001070#endif
1071
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001072int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001073PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyObject *m, *d, *v, *w, *oenc = NULL;
1076 mod_ty mod;
1077 PyArena *arena;
1078 char *ps1 = "", *ps2 = "", *enc = NULL;
1079 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (fp == stdin) {
1082 /* Fetch encoding from sys.stdin */
1083 v = PySys_GetObject("stdin");
1084 if (v == NULL || v == Py_None)
1085 return -1;
1086 oenc = PyObject_GetAttrString(v, "encoding");
1087 if (!oenc)
1088 return -1;
1089 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001090 if (enc == NULL)
1091 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 }
1093 v = PySys_GetObject("ps1");
1094 if (v != NULL) {
1095 v = PyObject_Str(v);
1096 if (v == NULL)
1097 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001098 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001100 if (ps1 == NULL) {
1101 PyErr_Clear();
1102 ps1 = "";
1103 }
1104 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 }
1106 w = PySys_GetObject("ps2");
1107 if (w != NULL) {
1108 w = PyObject_Str(w);
1109 if (w == NULL)
1110 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001111 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001113 if (ps2 == NULL) {
1114 PyErr_Clear();
1115 ps2 = "";
1116 }
1117 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 }
1119 arena = PyArena_New();
1120 if (arena == NULL) {
1121 Py_XDECREF(v);
1122 Py_XDECREF(w);
1123 Py_XDECREF(oenc);
1124 return -1;
1125 }
1126 mod = PyParser_ASTFromFile(fp, filename, enc,
1127 Py_single_input, ps1, ps2,
1128 flags, &errcode, arena);
1129 Py_XDECREF(v);
1130 Py_XDECREF(w);
1131 Py_XDECREF(oenc);
1132 if (mod == NULL) {
1133 PyArena_Free(arena);
1134 if (errcode == E_EOF) {
1135 PyErr_Clear();
1136 return E_EOF;
1137 }
1138 PyErr_Print();
1139 return -1;
1140 }
1141 m = PyImport_AddModule("__main__");
1142 if (m == NULL) {
1143 PyArena_Free(arena);
1144 return -1;
1145 }
1146 d = PyModule_GetDict(m);
1147 v = run_mod(mod, filename, d, d, flags, arena);
1148 PyArena_Free(arena);
1149 flush_io();
1150 if (v == NULL) {
1151 PyErr_Print();
1152 return -1;
1153 }
1154 Py_DECREF(v);
1155 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001156}
1157
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001158/* Check whether a file maybe a pyc file: Look at the extension,
1159 the file type, and, if we may close it, at the first few bytes. */
1160
1161static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001162maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1165 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 /* Only look into the file if we are allowed to close it, since
1168 it then should also be seekable. */
1169 if (closeit) {
1170 /* Read only two bytes of the magic. If the file was opened in
1171 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1172 be read as they are on disk. */
1173 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1174 unsigned char buf[2];
1175 /* Mess: In case of -x, the stream is NOT at its start now,
1176 and ungetc() was used to push back the first newline,
1177 which makes the current stream position formally undefined,
1178 and a x-platform nightmare.
1179 Unfortunately, we have no direct way to know whether -x
1180 was specified. So we use a terrible hack: if the current
1181 stream position is not 0, we assume -x was specified, and
1182 give up. Bug 132850 on SourceForge spells out the
1183 hopelessness of trying anything else (fseek and ftell
1184 don't work predictably x-platform for text-mode files).
1185 */
1186 int ispyc = 0;
1187 if (ftell(fp) == 0) {
1188 if (fread(buf, 1, 2, fp) == 2 &&
1189 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1190 ispyc = 1;
1191 rewind(fp);
1192 }
1193 return ispyc;
1194 }
1195 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001196}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001197
Guido van Rossum0df002c2000-08-27 19:21:52 +00001198int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001199PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 PyObject *m, *d, *v;
1203 const char *ext;
1204 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 m = PyImport_AddModule("__main__");
1207 if (m == NULL)
1208 return -1;
1209 d = PyModule_GetDict(m);
1210 if (PyDict_GetItemString(d, "__file__") == NULL) {
1211 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001212 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (f == NULL)
1214 return -1;
1215 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1216 Py_DECREF(f);
1217 return -1;
1218 }
1219 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1220 return -1;
1221 set_file_name = 1;
1222 Py_DECREF(f);
1223 }
1224 len = strlen(filename);
1225 ext = filename + len - (len > 4 ? 4 : 0);
1226 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1227 /* Try to run a pyc file. First, re-open in binary */
1228 if (closeit)
1229 fclose(fp);
1230 if ((fp = fopen(filename, "rb")) == NULL) {
1231 fprintf(stderr, "python: Can't reopen .pyc file\n");
1232 ret = -1;
1233 goto done;
1234 }
1235 /* Turn on optimization if a .pyo file is given */
1236 if (strcmp(ext, ".pyo") == 0)
1237 Py_OptimizeFlag = 1;
1238 v = run_pyc_file(fp, filename, d, d, flags);
1239 } else {
1240 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1241 closeit, flags);
1242 }
1243 flush_io();
1244 if (v == NULL) {
1245 PyErr_Print();
1246 ret = -1;
1247 goto done;
1248 }
1249 Py_DECREF(v);
1250 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001251 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1253 PyErr_Clear();
1254 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001255}
1256
1257int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001258PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 PyObject *m, *d, *v;
1261 m = PyImport_AddModule("__main__");
1262 if (m == NULL)
1263 return -1;
1264 d = PyModule_GetDict(m);
1265 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1266 if (v == NULL) {
1267 PyErr_Print();
1268 return -1;
1269 }
1270 Py_DECREF(v);
1271 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001272}
1273
Barry Warsaw035574d1997-08-29 22:07:17 +00001274static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001275parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 long hold;
1279 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 /* old style errors */
1282 if (PyTuple_Check(err))
1283 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1284 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (! (v = PyObject_GetAttrString(err, "msg")))
1289 goto finally;
1290 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (!(v = PyObject_GetAttrString(err, "filename")))
1293 goto finally;
1294 if (v == Py_None)
1295 *filename = NULL;
1296 else if (! (*filename = _PyUnicode_AsString(v)))
1297 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 Py_DECREF(v);
1300 if (!(v = PyObject_GetAttrString(err, "lineno")))
1301 goto finally;
1302 hold = PyLong_AsLong(v);
1303 Py_DECREF(v);
1304 v = NULL;
1305 if (hold < 0 && PyErr_Occurred())
1306 goto finally;
1307 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if (!(v = PyObject_GetAttrString(err, "offset")))
1310 goto finally;
1311 if (v == Py_None) {
1312 *offset = -1;
1313 Py_DECREF(v);
1314 v = NULL;
1315 } else {
1316 hold = PyLong_AsLong(v);
1317 Py_DECREF(v);
1318 v = NULL;
1319 if (hold < 0 && PyErr_Occurred())
1320 goto finally;
1321 *offset = (int)hold;
1322 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 if (!(v = PyObject_GetAttrString(err, "text")))
1325 goto finally;
1326 if (v == Py_None)
1327 *text = NULL;
1328 else if (!PyUnicode_Check(v) ||
1329 !(*text = _PyUnicode_AsString(v)))
1330 goto finally;
1331 Py_DECREF(v);
1332 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001333
1334finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 Py_XDECREF(v);
1336 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001337}
1338
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001339void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001340PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001343}
1344
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001345static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001346print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 char *nl;
1349 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001350 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1351 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 for (;;) {
1353 nl = strchr(text, '\n');
1354 if (nl == NULL || nl-text >= offset)
1355 break;
1356 offset -= (int)(nl+1-text);
1357 text = nl+1;
1358 }
1359 while (*text == ' ' || *text == '\t') {
1360 text++;
1361 offset--;
1362 }
1363 }
1364 PyFile_WriteString(" ", f);
1365 PyFile_WriteString(text, f);
1366 if (*text == '\0' || text[strlen(text)-1] != '\n')
1367 PyFile_WriteString("\n", f);
1368 if (offset == -1)
1369 return;
1370 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001371 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001374}
1375
Guido van Rossum66e8e862001-03-23 17:54:43 +00001376static void
1377handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 PyObject *exception, *value, *tb;
1380 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 if (Py_InspectFlag)
1383 /* Don't exit if -i flag was given. This flag is set to 0
1384 * when entering interactive mode for inspecting. */
1385 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 PyErr_Fetch(&exception, &value, &tb);
1388 fflush(stdout);
1389 if (value == NULL || value == Py_None)
1390 goto done;
1391 if (PyExceptionInstance_Check(value)) {
1392 /* The error code should be in the `code' attribute. */
1393 PyObject *code = PyObject_GetAttrString(value, "code");
1394 if (code) {
1395 Py_DECREF(value);
1396 value = code;
1397 if (value == Py_None)
1398 goto done;
1399 }
1400 /* If we failed to dig out the 'code' attribute,
1401 just let the else clause below print the error. */
1402 }
1403 if (PyLong_Check(value))
1404 exitcode = (int)PyLong_AsLong(value);
1405 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001406 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001407 if (sys_stderr != NULL && sys_stderr != Py_None) {
1408 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1409 } else {
1410 PyObject_Print(value, stderr, Py_PRINT_RAW);
1411 fflush(stderr);
1412 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 PySys_WriteStderr("\n");
1414 exitcode = 1;
1415 }
Tim Peterscf615b52003-04-19 18:47:02 +00001416 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 /* Restore and clear the exception info, in order to properly decref
1418 * the exception, value, and traceback. If we just exit instead,
1419 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1420 * some finalizers from running.
1421 */
1422 PyErr_Restore(exception, value, tb);
1423 PyErr_Clear();
1424 Py_Exit(exitcode);
1425 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001426}
1427
1428void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001429PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1434 handle_system_exit();
1435 }
1436 PyErr_Fetch(&exception, &v, &tb);
1437 if (exception == NULL)
1438 return;
1439 PyErr_NormalizeException(&exception, &v, &tb);
1440 if (tb == NULL) {
1441 tb = Py_None;
1442 Py_INCREF(tb);
1443 }
1444 PyException_SetTraceback(v, tb);
1445 if (exception == NULL)
1446 return;
1447 /* Now we know v != NULL too */
1448 if (set_sys_last_vars) {
1449 PySys_SetObject("last_type", exception);
1450 PySys_SetObject("last_value", v);
1451 PySys_SetObject("last_traceback", tb);
1452 }
1453 hook = PySys_GetObject("excepthook");
1454 if (hook) {
1455 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1456 PyObject *result = PyEval_CallObject(hook, args);
1457 if (result == NULL) {
1458 PyObject *exception2, *v2, *tb2;
1459 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1460 handle_system_exit();
1461 }
1462 PyErr_Fetch(&exception2, &v2, &tb2);
1463 PyErr_NormalizeException(&exception2, &v2, &tb2);
1464 /* It should not be possible for exception2 or v2
1465 to be NULL. However PyErr_Display() can't
1466 tolerate NULLs, so just be safe. */
1467 if (exception2 == NULL) {
1468 exception2 = Py_None;
1469 Py_INCREF(exception2);
1470 }
1471 if (v2 == NULL) {
1472 v2 = Py_None;
1473 Py_INCREF(v2);
1474 }
1475 fflush(stdout);
1476 PySys_WriteStderr("Error in sys.excepthook:\n");
1477 PyErr_Display(exception2, v2, tb2);
1478 PySys_WriteStderr("\nOriginal exception was:\n");
1479 PyErr_Display(exception, v, tb);
1480 Py_DECREF(exception2);
1481 Py_DECREF(v2);
1482 Py_XDECREF(tb2);
1483 }
1484 Py_XDECREF(result);
1485 Py_XDECREF(args);
1486 } else {
1487 PySys_WriteStderr("sys.excepthook is missing\n");
1488 PyErr_Display(exception, v, tb);
1489 }
1490 Py_XDECREF(exception);
1491 Py_XDECREF(v);
1492 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001493}
1494
Benjamin Petersone6528212008-07-15 15:32:09 +00001495static void
1496print_exception(PyObject *f, PyObject *value)
1497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 int err = 0;
1499 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (!PyExceptionInstance_Check(value)) {
1502 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1503 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1504 PyFile_WriteString(" found\n", f);
1505 return;
1506 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 Py_INCREF(value);
1509 fflush(stdout);
1510 type = (PyObject *) Py_TYPE(value);
1511 tb = PyException_GetTraceback(value);
1512 if (tb && tb != Py_None)
1513 err = PyTraceBack_Print(tb, f);
1514 if (err == 0 &&
1515 PyObject_HasAttrString(value, "print_file_and_line"))
1516 {
1517 PyObject *message;
1518 const char *filename, *text;
1519 int lineno, offset;
1520 if (!parse_syntax_error(value, &message, &filename,
1521 &lineno, &offset, &text))
1522 PyErr_Clear();
1523 else {
1524 char buf[10];
1525 PyFile_WriteString(" File \"", f);
1526 if (filename == NULL)
1527 PyFile_WriteString("<string>", f);
1528 else
1529 PyFile_WriteString(filename, f);
1530 PyFile_WriteString("\", line ", f);
1531 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1532 PyFile_WriteString(buf, f);
1533 PyFile_WriteString("\n", f);
1534 if (text != NULL)
1535 print_error_text(f, offset, text);
1536 Py_DECREF(value);
1537 value = message;
1538 /* Can't be bothered to check all those
1539 PyFile_WriteString() calls */
1540 if (PyErr_Occurred())
1541 err = -1;
1542 }
1543 }
1544 if (err) {
1545 /* Don't do anything else */
1546 }
1547 else {
1548 PyObject* moduleName;
1549 char* className;
1550 assert(PyExceptionClass_Check(type));
1551 className = PyExceptionClass_Name(type);
1552 if (className != NULL) {
1553 char *dot = strrchr(className, '.');
1554 if (dot != NULL)
1555 className = dot+1;
1556 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 moduleName = PyObject_GetAttrString(type, "__module__");
1559 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1560 {
1561 Py_DECREF(moduleName);
1562 err = PyFile_WriteString("<unknown>", f);
1563 }
1564 else {
1565 char* modstr = _PyUnicode_AsString(moduleName);
1566 if (modstr && strcmp(modstr, "builtins"))
1567 {
1568 err = PyFile_WriteString(modstr, f);
1569 err += PyFile_WriteString(".", f);
1570 }
1571 Py_DECREF(moduleName);
1572 }
1573 if (err == 0) {
1574 if (className == NULL)
1575 err = PyFile_WriteString("<unknown>", f);
1576 else
1577 err = PyFile_WriteString(className, f);
1578 }
1579 }
1580 if (err == 0 && (value != Py_None)) {
1581 PyObject *s = PyObject_Str(value);
1582 /* only print colon if the str() of the
1583 object is not the empty string
1584 */
1585 if (s == NULL)
1586 err = -1;
1587 else if (!PyUnicode_Check(s) ||
1588 PyUnicode_GetSize(s) != 0)
1589 err = PyFile_WriteString(": ", f);
1590 if (err == 0)
1591 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1592 Py_XDECREF(s);
1593 }
1594 /* try to write a newline in any case */
1595 err += PyFile_WriteString("\n", f);
1596 Py_XDECREF(tb);
1597 Py_DECREF(value);
1598 /* If an error happened here, don't show it.
1599 XXX This is wrong, but too many callers rely on this behavior. */
1600 if (err != 0)
1601 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001602}
1603
1604static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 "\nThe above exception was the direct cause "
1606 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001607
1608static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 "\nDuring handling of the above exception, "
1610 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001611
1612static void
1613print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 int err = 0, res;
1616 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (seen != NULL) {
1619 /* Exception chaining */
1620 if (PySet_Add(seen, value) == -1)
1621 PyErr_Clear();
1622 else if (PyExceptionInstance_Check(value)) {
1623 cause = PyException_GetCause(value);
1624 context = PyException_GetContext(value);
1625 if (cause) {
1626 res = PySet_Contains(seen, cause);
1627 if (res == -1)
1628 PyErr_Clear();
1629 if (res == 0) {
1630 print_exception_recursive(
1631 f, cause, seen);
1632 err |= PyFile_WriteString(
1633 cause_message, f);
1634 }
1635 }
1636 else if (context) {
1637 res = PySet_Contains(seen, context);
1638 if (res == -1)
1639 PyErr_Clear();
1640 if (res == 0) {
1641 print_exception_recursive(
1642 f, context, seen);
1643 err |= PyFile_WriteString(
1644 context_message, f);
1645 }
1646 }
1647 Py_XDECREF(context);
1648 Py_XDECREF(cause);
1649 }
1650 }
1651 print_exception(f, value);
1652 if (err != 0)
1653 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001654}
1655
Thomas Wouters477c8d52006-05-27 19:21:47 +00001656void
1657PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 PyObject *seen;
1660 PyObject *f = PySys_GetObject("stderr");
1661 if (f == Py_None) {
1662 /* pass */
1663 }
1664 else if (f == NULL) {
1665 _PyObject_Dump(value);
1666 fprintf(stderr, "lost sys.stderr\n");
1667 }
1668 else {
1669 /* We choose to ignore seen being possibly NULL, and report
1670 at least the main exception (it could be a MemoryError).
1671 */
1672 seen = PySet_New(NULL);
1673 if (seen == NULL)
1674 PyErr_Clear();
1675 print_exception_recursive(f, value, seen);
1676 Py_XDECREF(seen);
1677 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001678}
1679
Guido van Rossum82598051997-03-05 00:20:32 +00001680PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001681PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 PyObject *ret = NULL;
1685 mod_ty mod;
1686 PyArena *arena = PyArena_New();
1687 if (arena == NULL)
1688 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1691 if (mod != NULL)
1692 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1693 PyArena_Free(arena);
1694 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001695}
1696
1697PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001698PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 PyObject *ret;
1702 mod_ty mod;
1703 PyArena *arena = PyArena_New();
1704 if (arena == NULL)
1705 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1708 flags, NULL, arena);
1709 if (closeit)
1710 fclose(fp);
1711 if (mod == NULL) {
1712 PyArena_Free(arena);
1713 return NULL;
1714 }
1715 ret = run_mod(mod, filename, globals, locals, flags, arena);
1716 PyArena_Free(arena);
1717 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001718}
1719
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001720static void
1721flush_io(void)
1722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 PyObject *f, *r;
1724 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 /* Save the current exception */
1727 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 f = PySys_GetObject("stderr");
1730 if (f != NULL) {
1731 r = PyObject_CallMethod(f, "flush", "");
1732 if (r)
1733 Py_DECREF(r);
1734 else
1735 PyErr_Clear();
1736 }
1737 f = PySys_GetObject("stdout");
1738 if (f != NULL) {
1739 r = PyObject_CallMethod(f, "flush", "");
1740 if (r)
1741 Py_DECREF(r);
1742 else
1743 PyErr_Clear();
1744 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001747}
1748
Guido van Rossum82598051997-03-05 00:20:32 +00001749static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001750run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 PyCodeObject *co;
1754 PyObject *v;
1755 co = PyAST_Compile(mod, filename, flags, arena);
1756 if (co == NULL)
1757 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001758 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 Py_DECREF(co);
1760 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001761}
1762
Guido van Rossum82598051997-03-05 00:20:32 +00001763static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001764run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 PyCodeObject *co;
1768 PyObject *v;
1769 long magic;
1770 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 magic = PyMarshal_ReadLongFromFile(fp);
1773 if (magic != PyImport_GetMagicNumber()) {
1774 PyErr_SetString(PyExc_RuntimeError,
1775 "Bad magic number in .pyc file");
1776 return NULL;
1777 }
1778 (void) PyMarshal_ReadLongFromFile(fp);
1779 v = PyMarshal_ReadLastObjectFromFile(fp);
1780 fclose(fp);
1781 if (v == NULL || !PyCode_Check(v)) {
1782 Py_XDECREF(v);
1783 PyErr_SetString(PyExc_RuntimeError,
1784 "Bad code object in .pyc file");
1785 return NULL;
1786 }
1787 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001788 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (v && flags)
1790 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1791 Py_DECREF(co);
1792 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001793}
1794
Guido van Rossum82598051997-03-05 00:20:32 +00001795PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001796Py_CompileStringExFlags(const char *str, const char *filename, int start,
1797 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 PyCodeObject *co;
1800 mod_ty mod;
1801 PyArena *arena = PyArena_New();
1802 if (arena == NULL)
1803 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1806 if (mod == NULL) {
1807 PyArena_Free(arena);
1808 return NULL;
1809 }
1810 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1811 PyObject *result = PyAST_mod2obj(mod);
1812 PyArena_Free(arena);
1813 return result;
1814 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001815 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 PyArena_Free(arena);
1817 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001818}
1819
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001820/* For use in Py_LIMITED_API */
1821#undef Py_CompileString
1822PyObject *
1823PyCompileString(const char *str, const char *filename, int start)
1824{
1825 return Py_CompileStringFlags(str, filename, start, NULL);
1826}
1827
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001828struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001829Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 struct symtable *st;
1832 mod_ty mod;
1833 PyCompilerFlags flags;
1834 PyArena *arena = PyArena_New();
1835 if (arena == NULL)
1836 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 flags.cf_flags = 0;
1839 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1840 if (mod == NULL) {
1841 PyArena_Free(arena);
1842 return NULL;
1843 }
1844 st = PySymtable_Build(mod, filename, 0);
1845 PyArena_Free(arena);
1846 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001847}
1848
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849/* Preferred access to parser is through AST. */
1850mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001851PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 mod_ty mod;
1855 PyCompilerFlags localflags;
1856 perrdetail err;
1857 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1860 &_PyParser_Grammar, start, &err,
1861 &iflags);
1862 if (flags == NULL) {
1863 localflags.cf_flags = 0;
1864 flags = &localflags;
1865 }
1866 if (n) {
1867 flags->cf_flags |= iflags & PyCF_MASK;
1868 mod = PyAST_FromNode(n, flags, filename, arena);
1869 PyNode_Free(n);
1870 return mod;
1871 }
1872 else {
1873 err_input(&err);
1874 return NULL;
1875 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001876}
1877
1878mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001879PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 int start, char *ps1,
1881 char *ps2, PyCompilerFlags *flags, int *errcode,
1882 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 mod_ty mod;
1885 PyCompilerFlags localflags;
1886 perrdetail err;
1887 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1890 &_PyParser_Grammar,
1891 start, ps1, ps2, &err, &iflags);
1892 if (flags == NULL) {
1893 localflags.cf_flags = 0;
1894 flags = &localflags;
1895 }
1896 if (n) {
1897 flags->cf_flags |= iflags & PyCF_MASK;
1898 mod = PyAST_FromNode(n, flags, filename, arena);
1899 PyNode_Free(n);
1900 return mod;
1901 }
1902 else {
1903 err_input(&err);
1904 if (errcode)
1905 *errcode = err.error;
1906 return NULL;
1907 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908}
1909
Guido van Rossuma110aa61994-08-29 12:50:44 +00001910/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001911
Guido van Rossuma110aa61994-08-29 12:50:44 +00001912node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001913PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 perrdetail err;
1916 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1917 &_PyParser_Grammar,
1918 start, NULL, NULL, &err, flags);
1919 if (n == NULL)
1920 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001923}
1924
Guido van Rossuma110aa61994-08-29 12:50:44 +00001925/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001926
Guido van Rossuma110aa61994-08-29 12:50:44 +00001927node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001928PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 perrdetail err;
1931 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1932 start, &err, flags);
1933 if (n == NULL)
1934 err_input(&err);
1935 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001936}
1937
1938node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001939PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 perrdetail err;
1943 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1944 &_PyParser_Grammar, start, &err, flags);
1945 if (n == NULL)
1946 err_input(&err);
1947 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001948}
1949
1950node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001951PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001954}
1955
Guido van Rossum66ebd912003-04-17 16:02:26 +00001956/* May want to move a more generalized form of this to parsetok.c or
1957 even parser modules. */
1958
1959void
1960PyParser_SetError(perrdetail *err)
1961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001963}
1964
Guido van Rossuma110aa61994-08-29 12:50:44 +00001965/* Set the error appropriate to the given input error code (see errcode.h) */
1966
1967static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001968err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 PyObject *v, *w, *errtype, *errtext;
1971 PyObject *msg_obj = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001972 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 errtype = PyExc_SyntaxError;
1976 switch (err->error) {
1977 case E_ERROR:
1978 return;
1979 case E_SYNTAX:
1980 errtype = PyExc_IndentationError;
1981 if (err->expected == INDENT)
1982 msg = "expected an indented block";
1983 else if (err->token == INDENT)
1984 msg = "unexpected indent";
1985 else if (err->token == DEDENT)
1986 msg = "unexpected unindent";
1987 else {
1988 errtype = PyExc_SyntaxError;
1989 msg = "invalid syntax";
1990 }
1991 break;
1992 case E_TOKEN:
1993 msg = "invalid token";
1994 break;
1995 case E_EOFS:
1996 msg = "EOF while scanning triple-quoted string literal";
1997 break;
1998 case E_EOLS:
1999 msg = "EOL while scanning string literal";
2000 break;
2001 case E_INTR:
2002 if (!PyErr_Occurred())
2003 PyErr_SetNone(PyExc_KeyboardInterrupt);
2004 goto cleanup;
2005 case E_NOMEM:
2006 PyErr_NoMemory();
2007 goto cleanup;
2008 case E_EOF:
2009 msg = "unexpected EOF while parsing";
2010 break;
2011 case E_TABSPACE:
2012 errtype = PyExc_TabError;
2013 msg = "inconsistent use of tabs and spaces in indentation";
2014 break;
2015 case E_OVERFLOW:
2016 msg = "expression too long";
2017 break;
2018 case E_DEDENT:
2019 errtype = PyExc_IndentationError;
2020 msg = "unindent does not match any outer indentation level";
2021 break;
2022 case E_TOODEEP:
2023 errtype = PyExc_IndentationError;
2024 msg = "too many levels of indentation";
2025 break;
2026 case E_DECODE: {
2027 PyObject *type, *value, *tb;
2028 PyErr_Fetch(&type, &value, &tb);
2029 msg = "unknown decode error";
2030 if (value != NULL)
2031 msg_obj = PyObject_Str(value);
2032 Py_XDECREF(type);
2033 Py_XDECREF(value);
2034 Py_XDECREF(tb);
2035 break;
2036 }
2037 case E_LINECONT:
2038 msg = "unexpected character after line continuation character";
2039 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 case E_IDENTIFIER:
2042 msg = "invalid character in identifier";
2043 break;
2044 default:
2045 fprintf(stderr, "error=%d\n", err->error);
2046 msg = "unknown parsing error";
2047 break;
2048 }
2049 /* err->text may not be UTF-8 in case of decoding errors.
2050 Explicitly convert to an object. */
2051 if (!err->text) {
2052 errtext = Py_None;
2053 Py_INCREF(Py_None);
2054 } else {
2055 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2056 "replace");
2057 }
Victor Stinner2f2ed1f2010-10-16 13:42:53 +00002058 if (err->filename != NULL)
2059 filename = PyUnicode_DecodeFSDefault(err->filename);
2060 else {
2061 Py_INCREF(Py_None);
2062 filename = Py_None;
2063 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002064 if (filename != NULL)
2065 v = Py_BuildValue("(NiiN)", filename,
2066 err->lineno, err->offset, errtext);
2067 else
2068 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 if (v != NULL) {
2070 if (msg_obj)
2071 w = Py_BuildValue("(OO)", msg_obj, v);
2072 else
2073 w = Py_BuildValue("(sO)", msg, v);
2074 } else
2075 w = NULL;
2076 Py_XDECREF(v);
2077 PyErr_SetObject(errtype, w);
2078 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002079cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 Py_XDECREF(msg_obj);
2081 if (err->text != NULL) {
2082 PyObject_FREE(err->text);
2083 err->text = NULL;
2084 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002085}
2086
2087/* Print fatal error message and abort */
2088
2089void
Tim Peters7c321a82002-07-09 02:57:01 +00002090Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 fprintf(stderr, "Fatal Python error: %s\n", msg);
2093 fflush(stderr); /* it helps in Windows debug build */
2094 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002095 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002097#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 {
2099 size_t len = strlen(msg);
2100 WCHAR* buffer;
2101 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 /* Convert the message to wchar_t. This uses a simple one-to-one
2104 conversion, assuming that the this error message actually uses ASCII
2105 only. If this ceases to be true, we will have to convert. */
2106 buffer = alloca( (len+1) * (sizeof *buffer));
2107 for( i=0; i<=len; ++i)
2108 buffer[i] = msg[i];
2109 OutputDebugStringW(L"Fatal Python error: ");
2110 OutputDebugStringW(buffer);
2111 OutputDebugStringW(L"\n");
2112 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002113#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002115#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002116#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002118}
2119
2120/* Clean up and exit */
2121
Guido van Rossuma110aa61994-08-29 12:50:44 +00002122#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002123#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002124#endif
2125
Collin Winter670e6922007-03-21 02:57:17 +00002126static void (*pyexitfunc)(void) = NULL;
2127/* For the atexit module. */
2128void _Py_PyAtExit(void (*func)(void))
2129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002131}
2132
2133static void
2134call_py_exitfuncs(void)
2135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 if (pyexitfunc == NULL)
2137 return;
Collin Winter670e6922007-03-21 02:57:17 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 (*pyexitfunc)();
2140 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002141}
2142
Antoine Pitrou011bd622009-10-20 21:52:47 +00002143/* Wait until threading._shutdown completes, provided
2144 the threading module was imported in the first place.
2145 The shutdown routine will wait until all non-daemon
2146 "threading" threads have completed. */
2147static void
2148wait_for_thread_shutdown(void)
2149{
2150#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 PyObject *result;
2152 PyThreadState *tstate = PyThreadState_GET();
2153 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2154 "threading");
2155 if (threading == NULL) {
2156 /* threading not imported */
2157 PyErr_Clear();
2158 return;
2159 }
2160 result = PyObject_CallMethod(threading, "_shutdown", "");
2161 if (result == NULL) {
2162 PyErr_WriteUnraisable(threading);
2163 }
2164 else {
2165 Py_DECREF(result);
2166 }
2167 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002168#endif
2169}
2170
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002171#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002172static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002173static int nexitfuncs = 0;
2174
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002175int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 if (nexitfuncs >= NEXITFUNCS)
2178 return -1;
2179 exitfuncs[nexitfuncs++] = func;
2180 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002181}
2182
Guido van Rossumcc283f51997-08-05 02:22:03 +00002183static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002184call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 while (nexitfuncs > 0)
2187 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 fflush(stdout);
2190 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002191}
2192
2193void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002194Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002199}
2200
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002201static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002202initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002203{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002204#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002206#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002207#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002209#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002210#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002212#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002214}
2215
Guido van Rossum7433b121997-02-14 19:45:36 +00002216
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002217/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2218 *
2219 * All of the code in this function must only use async-signal-safe functions,
2220 * listed at `man 7 signal` or
2221 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2222 */
2223void
2224_Py_RestoreSignals(void)
2225{
2226#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002228#endif
2229#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002231#endif
2232#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002234#endif
2235}
2236
2237
Guido van Rossum7433b121997-02-14 19:45:36 +00002238/*
2239 * The file descriptor fd is considered ``interactive'' if either
2240 * a) isatty(fd) is TRUE, or
2241 * b) the -i flag was given, and the filename associated with
2242 * the descriptor is NULL or "<stdin>" or "???".
2243 */
2244int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002245Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (isatty((int)fileno(fp)))
2248 return 1;
2249 if (!Py_InteractiveFlag)
2250 return 0;
2251 return (filename == NULL) ||
2252 (strcmp(filename, "<stdin>") == 0) ||
2253 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002254}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002255
2256
Tim Petersd08e3822003-04-17 15:24:21 +00002257#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002258#if defined(WIN32) && defined(_MSC_VER)
2259
2260/* Stack checking for Microsoft C */
2261
2262#include <malloc.h>
2263#include <excpt.h>
2264
Fred Drakee8de31c2000-08-31 05:38:39 +00002265/*
2266 * Return non-zero when we run out of memory on the stack; zero otherwise.
2267 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002268int
Fred Drake399739f2000-08-31 05:52:44 +00002269PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 __try {
2272 /* alloca throws a stack overflow exception if there's
2273 not enough space left on the stack */
2274 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2275 return 0;
2276 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2277 EXCEPTION_EXECUTE_HANDLER :
2278 EXCEPTION_CONTINUE_SEARCH) {
2279 int errcode = _resetstkoflw();
2280 if (errcode == 0)
2281 {
2282 Py_FatalError("Could not reset the stack!");
2283 }
2284 }
2285 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002286}
2287
2288#endif /* WIN32 && _MSC_VER */
2289
2290/* Alternate implementations can be added here... */
2291
2292#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002293
2294
2295/* Wrappers around sigaction() or signal(). */
2296
2297PyOS_sighandler_t
2298PyOS_getsig(int sig)
2299{
2300#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 struct sigaction context;
2302 if (sigaction(sig, NULL, &context) == -1)
2303 return SIG_ERR;
2304 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002305#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002307/* Special signal handling for the secure CRT in Visual Studio 2005 */
2308#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 switch (sig) {
2310 /* Only these signals are valid */
2311 case SIGINT:
2312 case SIGILL:
2313 case SIGFPE:
2314 case SIGSEGV:
2315 case SIGTERM:
2316 case SIGBREAK:
2317 case SIGABRT:
2318 break;
2319 /* Don't call signal() with other values or it will assert */
2320 default:
2321 return SIG_ERR;
2322 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002323#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 handler = signal(sig, SIG_IGN);
2325 if (handler != SIG_ERR)
2326 signal(sig, handler);
2327 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002328#endif
2329}
2330
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002331/*
2332 * All of the code in this function must only use async-signal-safe functions,
2333 * listed at `man 7 signal` or
2334 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2335 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002336PyOS_sighandler_t
2337PyOS_setsig(int sig, PyOS_sighandler_t handler)
2338{
2339#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 /* Some code in Modules/signalmodule.c depends on sigaction() being
2341 * used here if HAVE_SIGACTION is defined. Fix that if this code
2342 * changes to invalidate that assumption.
2343 */
2344 struct sigaction context, ocontext;
2345 context.sa_handler = handler;
2346 sigemptyset(&context.sa_mask);
2347 context.sa_flags = 0;
2348 if (sigaction(sig, &context, &ocontext) == -1)
2349 return SIG_ERR;
2350 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002351#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 PyOS_sighandler_t oldhandler;
2353 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002354#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002356#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002358#endif
2359}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360
2361/* Deprecated C API functions still provided for binary compatiblity */
2362
2363#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002364PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002365PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002368}
2369
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002370#undef PyParser_SimpleParseString
2371PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002372PyParser_SimpleParseString(const char *str, int start)
2373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002375}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002376
2377#undef PyRun_AnyFile
2378PyAPI_FUNC(int)
2379PyRun_AnyFile(FILE *fp, const char *name)
2380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002382}
2383
2384#undef PyRun_AnyFileEx
2385PyAPI_FUNC(int)
2386PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002389}
2390
2391#undef PyRun_AnyFileFlags
2392PyAPI_FUNC(int)
2393PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002396}
2397
2398#undef PyRun_File
2399PyAPI_FUNC(PyObject *)
2400PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002403}
2404
2405#undef PyRun_FileEx
2406PyAPI_FUNC(PyObject *)
2407PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002410}
2411
2412#undef PyRun_FileFlags
2413PyAPI_FUNC(PyObject *)
2414PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002418}
2419
2420#undef PyRun_SimpleFile
2421PyAPI_FUNC(int)
2422PyRun_SimpleFile(FILE *f, const char *p)
2423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002425}
2426
2427#undef PyRun_SimpleFileEx
2428PyAPI_FUNC(int)
2429PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002432}
2433
2434
2435#undef PyRun_String
2436PyAPI_FUNC(PyObject *)
2437PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002440}
2441
2442#undef PyRun_SimpleString
2443PyAPI_FUNC(int)
2444PyRun_SimpleString(const char *s)
2445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002447}
2448
2449#undef Py_CompileString
2450PyAPI_FUNC(PyObject *)
2451Py_CompileString(const char *str, const char *p, int s)
2452{
Georg Brandl8334fd92010-12-04 10:26:46 +00002453 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2454}
2455
2456#undef Py_CompileStringFlags
2457PyAPI_FUNC(PyObject *)
2458Py_CompileStringFlags(const char *str, const char *p, int s,
2459 PyCompilerFlags *flags)
2460{
2461 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002462}
2463
2464#undef PyRun_InteractiveOne
2465PyAPI_FUNC(int)
2466PyRun_InteractiveOne(FILE *f, const char *p)
2467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002469}
2470
2471#undef PyRun_InteractiveLoop
2472PyAPI_FUNC(int)
2473PyRun_InteractiveLoop(FILE *f, const char *p)
2474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002476}
2477
2478#ifdef __cplusplus
2479}
2480#endif