blob: 33f187386a013e2c754d297406b22a9673c9b69e [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 */
Georg Brandl8aa7e992010-12-28 18:30:18 +000081int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000082int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000083int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000084int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000085int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000086int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000087int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000088int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000089int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000090int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000091int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000092
Christian Heimes33fe8092008-04-13 13:53:33 +000093/* PyModule_GetWarningsModule is no longer necessary as of 2.6
94since _warnings is builtin. This API should not be used. */
95PyObject *
96PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000099}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000100
Guido van Rossum25ce5661997-08-02 03:10:38 +0000101static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000102
Thomas Wouters7e474022000-07-16 12:04:32 +0000103/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000104
105int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000106Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109}
110
Guido van Rossum25ce5661997-08-02 03:10:38 +0000111/* Global initializations. Can be undone by Py_Finalize(). Don't
112 call this twice without an intervening Py_Finalize() call. When
113 initializations fail, a fatal error is issued and the function does
114 not return. On return, the first thread and interpreter state have
115 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117 Locking: you must hold the interpreter lock while calling this.
118 (If the lock has not yet been initialized, that's equivalent to
119 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000122
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000123static int
124add_flag(int flag, const char *envs)
125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 int env = atoi(envs);
127 if (flag < env)
128 flag = env;
129 if (flag < 1)
130 flag = 1;
131 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000132}
133
Christian Heimes5833a2f2008-10-30 21:40:04 +0000134static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000135get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000136{
Victor Stinner94908bb2010-08-18 21:23:25 +0000137 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000138 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000139
Victor Stinner94908bb2010-08-18 21:23:25 +0000140 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 if (!codec)
142 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 name = PyObject_GetAttrString(codec, "name");
145 Py_CLEAR(codec);
146 if (!name)
147 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000148
Victor Stinner94908bb2010-08-18 21:23:25 +0000149 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner386fe712010-05-19 00:34:15 +0000150 if (name == NULL)
151 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000152 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000154 if (name_str == NULL) {
155 PyErr_NoMemory();
156 return NULL;
157 }
158 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000159
160error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000162 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000164}
Victor Stinner94908bb2010-08-18 21:23:25 +0000165
166#if defined(HAVE_LANGINFO_H) && defined(CODESET)
167static char*
168get_codeset(void)
169{
170 char* codeset = nl_langinfo(CODESET);
171 if (!codeset || codeset[0] == '\0') {
172 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
173 return NULL;
174 }
175 return get_codec_name(codeset);
176}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000177#endif
178
Guido van Rossuma027efa1997-05-05 20:56:21 +0000179void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000180Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 PyInterpreterState *interp;
183 PyThreadState *tstate;
184 PyObject *bimod, *sysmod, *pstderr;
185 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (initialized)
189 return;
190 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000191
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000192#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 /* Set up the LC_CTYPE locale, so we can obtain
194 the locale's charset without having to switch
195 locales. */
196 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000197#endif
198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
200 Py_DebugFlag = add_flag(Py_DebugFlag, p);
201 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
202 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
203 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
204 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
205 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
206 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 interp = PyInterpreterState_New();
209 if (interp == NULL)
210 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 tstate = PyThreadState_New(interp);
213 if (tstate == NULL)
214 Py_FatalError("Py_Initialize: can't make first thread");
215 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000216
Victor Stinner6961bd62010-08-17 22:26:51 +0000217#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000218 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
219 destroying the GIL might fail when it is being referenced from
220 another running thread (see issue #9901).
221 Instead we destroy the previously created GIL here, which ensures
222 that we can call Py_Initialize / Py_Finalize multiple times. */
223 _PyEval_FiniThreads();
224
225 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000226 _PyGILState_Init(interp, tstate);
227#endif /* WITH_THREAD */
228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (!_PyFrame_Init())
232 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (!_PyLong_Init())
235 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (!PyByteArray_Init())
238 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 interp->modules = PyDict_New();
243 if (interp->modules == NULL)
244 Py_FatalError("Py_Initialize: can't make modules dictionary");
245 interp->modules_reloading = PyDict_New();
246 if (interp->modules_reloading == NULL)
247 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 /* Init Unicode implementation; relies on the codec registry */
250 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 bimod = _PyBuiltin_Init();
253 if (bimod == NULL)
254 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000255 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 interp->builtins = PyModule_GetDict(bimod);
257 if (interp->builtins == NULL)
258 Py_FatalError("Py_Initialize: can't initialize builtins dict");
259 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 /* initialize builtin exceptions */
262 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 sysmod = _PySys_Init();
265 if (sysmod == NULL)
266 Py_FatalError("Py_Initialize: can't initialize sys");
267 interp->sysdict = PyModule_GetDict(sysmod);
268 if (interp->sysdict == NULL)
269 Py_FatalError("Py_Initialize: can't initialize sys dict");
270 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000271 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 PySys_SetPath(Py_GetPath());
273 PyDict_SetItemString(interp->sysdict, "modules",
274 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* Set up a preliminary stderr printer until we have enough
277 infrastructure for the io module in place. */
278 pstderr = PyFile_NewStdPrinter(fileno(stderr));
279 if (pstderr == NULL)
280 Py_FatalError("Py_Initialize: can't set preliminary stderr");
281 PySys_SetObject("stderr", pstderr);
282 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000283 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000288
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000289 /* Initialize _warnings. */
290 _PyWarnings_Init();
291
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000292 _PyTime_Init();
293
Victor Stinnerb744ba12010-05-15 12:27:16 +0000294 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 if (install_sigs)
297 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 initmain(); /* Module __main__ */
300 if (initstdio() < 0)
301 Py_FatalError(
302 "Py_Initialize: can't initialize sys standard streams");
303
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000304 /* Initialize warnings. */
305 if (PySys_HasWarnOptions()) {
306 PyObject *warnings_module = PyImport_ImportModule("warnings");
307 if (warnings_module == NULL) {
308 fprintf(stderr, "'import warnings' failed; traceback:\n");
309 PyErr_Print();
310 }
311 Py_XDECREF(warnings_module);
312 }
313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (!Py_NoSiteFlag)
315 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000316}
317
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000318void
319Py_Initialize(void)
320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000322}
323
324
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000325#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000326extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000327#endif
328
Guido van Rossume8432ac2007-07-09 15:04:50 +0000329/* Flush stdout and stderr */
330
Neal Norwitz2bad9702007-08-27 06:19:22 +0000331static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000332flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 PyObject *fout = PySys_GetObject("stdout");
335 PyObject *ferr = PySys_GetObject("stderr");
336 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (fout != NULL && fout != Py_None) {
339 tmp = PyObject_CallMethod(fout, "flush", "");
340 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000341 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 else
343 Py_DECREF(tmp);
344 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000345
Victor Stinner9467b212010-05-14 00:59:09 +0000346 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 tmp = PyObject_CallMethod(ferr, "flush", "");
348 if (tmp == NULL)
349 PyErr_Clear();
350 else
351 Py_DECREF(tmp);
352 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000353}
354
Guido van Rossum25ce5661997-08-02 03:10:38 +0000355/* Undo the effect of Py_Initialize().
356
357 Beware: if multiple interpreter and/or thread states exist, these
358 are not wiped out; only the current thread and interpreter state
359 are deleted. But since everything else is deleted, those other
360 interpreter and thread states should no longer be used.
361
362 (XXX We should do better, e.g. wipe out all interpreters and
363 threads.)
364
365 Locking: as above.
366
367*/
368
369void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000370Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 PyInterpreterState *interp;
373 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (!initialized)
376 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 /* The interpreter is still entirely intact at this point, and the
381 * exit funcs may be relying on that. In particular, if some thread
382 * or exit func is still waiting to do an import, the import machinery
383 * expects Py_IsInitialized() to return true. So don't say the
384 * interpreter is uninitialized until after the exit funcs have run.
385 * Note that Threading.py uses an exit func to do a join on all the
386 * threads created thru it, so this also protects pending imports in
387 * the threads created via Threading.
388 */
389 call_py_exitfuncs();
390 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 /* Flush stdout+stderr */
393 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Get current thread state and interpreter pointer */
396 tstate = PyThreadState_GET();
397 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 /* Disable signal handling */
400 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 /* Clear type lookup cache */
403 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 /* Collect garbage. This may call finalizers; it's nice to call these
406 * before all modules are destroyed.
407 * XXX If a __del__ or weakref callback is triggered here, and tries to
408 * XXX import a module, bad things can happen, because Python no
409 * XXX longer believes it's initialized.
410 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
411 * XXX is easy to provoke that way. I've also seen, e.g.,
412 * XXX Exception exceptions.ImportError: 'No module named sha'
413 * XXX in <function callback at 0x008F5718> ignored
414 * XXX but I'm unclear on exactly how that one happens. In any case,
415 * XXX I haven't seen a real-life report of either of these.
416 */
417 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000418#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 /* With COUNT_ALLOCS, it helps to run GC multiple times:
420 each collection might release some types from the type
421 list, so they become garbage. */
422 while (PyGC_Collect() > 0)
423 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000424#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000425 /* We run this while most interpreter state is still alive, so that
426 debug information can be printed out */
427 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Destroy all modules */
430 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 /* Flush stdout+stderr (again, in case more was printed) */
433 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* Collect final garbage. This disposes of cycles created by
436 * new-style class definitions, for example.
437 * XXX This is disabled because it caused too many problems. If
438 * XXX a __del__ or weakref callback triggers here, Python code has
439 * XXX a hard time running, because even the sys module has been
440 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
441 * XXX One symptom is a sequence of information-free messages
442 * XXX coming from threads (if a __del__ or callback is invoked,
443 * XXX other threads can execute too, and any exception they encounter
444 * XXX triggers a comedy of errors as subsystem after subsystem
445 * XXX fails to find what it *expects* to find in sys to help report
446 * XXX the exception and consequent unexpected failures). I've also
447 * XXX seen segfaults then, after adding print statements to the
448 * XXX Python code getting called.
449 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000450#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000452#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
455 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000458#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000460#endif
461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000463
Tim Peters9cf25ce2003-04-17 15:21:01 +0000464#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* Display all objects still alive -- this can invoke arbitrary
466 * __repr__ overrides, so requires a mostly-intact interpreter.
467 * Alas, a lot of stuff may still be alive now that will be cleaned
468 * up later.
469 */
470 if (Py_GETENV("PYTHONDUMPREFS"))
471 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000472#endif /* Py_TRACE_REFS */
473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* Clear interpreter state */
475 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 /* Now we decref the exception classes. After this point nothing
478 can raise an exception. That's okay, because each Fini() method
479 below has been checked to make sure no exceptions are ever
480 raised.
481 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000486#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000488#endif /* WITH_THREAD */
489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* Delete current thread */
491 PyThreadState_Swap(NULL);
492 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* Sundry finalizers */
495 PyMethod_Fini();
496 PyFrame_Fini();
497 PyCFunction_Fini();
498 PyTuple_Fini();
499 PyList_Fini();
500 PySet_Fini();
501 PyBytes_Fini();
502 PyByteArray_Fini();
503 PyLong_Fini();
504 PyFloat_Fini();
505 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Cleanup Unicode implementation */
508 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000511 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 free((char*)Py_FileSystemDefaultEncoding);
513 Py_FileSystemDefaultEncoding = NULL;
514 }
Christian Heimesc8967002007-11-30 10:18:26 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* XXX Still allocated:
517 - various static ad-hoc pointers to interned strings
518 - int and float free list blocks
519 - whatever various modules and libraries allocate
520 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000523
Tim Peters269b2a62003-04-17 19:52:29 +0000524#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Display addresses (& refcnts) of all objects still alive.
526 * An address can be used to find the repr of the object, printed
527 * above by _Py_PrintReferences.
528 */
529 if (Py_GETENV("PYTHONDUMPREFS"))
530 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000531#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000532#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (Py_GETENV("PYTHONMALLOCSTATS"))
534 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000535#endif
536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538}
539
540/* Create and initialize a new interpreter and thread, and return the
541 new thread. This requires that Py_Initialize() has been called
542 first.
543
544 Unsuccessful initialization yields a NULL pointer. Note that *no*
545 exception information is available even in this case -- the
546 exception information is held in the thread, and there is no
547 thread.
548
549 Locking: as above.
550
551*/
552
553PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000554Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyInterpreterState *interp;
557 PyThreadState *tstate, *save_tstate;
558 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (!initialized)
561 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 interp = PyInterpreterState_New();
564 if (interp == NULL)
565 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 tstate = PyThreadState_New(interp);
568 if (tstate == NULL) {
569 PyInterpreterState_Delete(interp);
570 return NULL;
571 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 interp->modules = PyDict_New();
578 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579
Victor Stinner49d3f252010-10-17 01:24:53 +0000580 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 if (bimod != NULL) {
582 interp->builtins = PyModule_GetDict(bimod);
583 if (interp->builtins == NULL)
584 goto handle_error;
585 Py_INCREF(interp->builtins);
586 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* initialize builtin exceptions */
589 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000590
Victor Stinner49d3f252010-10-17 01:24:53 +0000591 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (bimod != NULL && sysmod != NULL) {
593 PyObject *pstderr;
594 interp->sysdict = PyModule_GetDict(sysmod);
595 if (interp->sysdict == NULL)
596 goto handle_error;
597 Py_INCREF(interp->sysdict);
598 PySys_SetPath(Py_GetPath());
599 PyDict_SetItemString(interp->sysdict, "modules",
600 interp->modules);
601 /* Set up a preliminary stderr printer until we have enough
602 infrastructure for the io module in place. */
603 pstderr = PyFile_NewStdPrinter(fileno(stderr));
604 if (pstderr == NULL)
605 Py_FatalError("Py_Initialize: can't set preliminary stderr");
606 PySys_SetObject("stderr", pstderr);
607 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000608 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 _PyImportHooks_Init();
611 if (initstdio() < 0)
612 Py_FatalError(
613 "Py_Initialize: can't initialize sys standard streams");
614 initmain();
615 if (!Py_NoSiteFlag)
616 initsite();
617 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (!PyErr_Occurred())
620 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621
Thomas Wouters89f507f2006-12-13 04:49:30 +0000622handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 PyErr_Print();
626 PyThreadState_Clear(tstate);
627 PyThreadState_Swap(save_tstate);
628 PyThreadState_Delete(tstate);
629 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000632}
633
634/* Delete an interpreter and its last thread. This requires that the
635 given thread state is current, that the thread has no remaining
636 frames, and that it is its interpreter's only remaining thread.
637 It is a fatal error to violate these constraints.
638
639 (Py_Finalize() doesn't have these constraints -- it zaps
640 everything, regardless.)
641
642 Locking: as above.
643
644*/
645
646void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000647Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (tstate != PyThreadState_GET())
652 Py_FatalError("Py_EndInterpreter: thread is not current");
653 if (tstate->frame != NULL)
654 Py_FatalError("Py_EndInterpreter: thread still has a frame");
655 if (tstate != interp->tstate_head || tstate->next != NULL)
656 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyImport_Cleanup();
659 PyInterpreterState_Clear(interp);
660 PyThreadState_Swap(NULL);
661 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000662}
663
Martin v. Löwis790465f2008-04-05 20:41:37 +0000664static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000665
666void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000667Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (pn && *pn)
670 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000671}
672
Martin v. Löwis790465f2008-04-05 20:41:37 +0000673wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000674Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000677}
678
Martin v. Löwis790465f2008-04-05 20:41:37 +0000679static wchar_t *default_home = NULL;
680static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000681
682void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000683Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000686}
687
Martin v. Löwis790465f2008-04-05 20:41:37 +0000688wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000689Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 wchar_t *home = default_home;
692 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
693 char* chome = Py_GETENV("PYTHONHOME");
694 if (chome) {
695 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
696 if (r != (size_t)-1 && r <= PATH_MAX)
697 home = env_home;
698 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 }
701 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000702}
703
Guido van Rossum6135a871995-01-09 17:53:26 +0000704/* Create __main__ module */
705
706static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000707initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PyObject *m, *d;
710 m = PyImport_AddModule("__main__");
711 if (m == NULL)
712 Py_FatalError("can't create __main__ module");
713 d = PyModule_GetDict(m);
714 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
715 PyObject *bimod = PyImport_ImportModule("builtins");
716 if (bimod == NULL ||
717 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
718 Py_FatalError("can't add __builtins__ to __main__");
719 Py_DECREF(bimod);
720 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000721}
722
Victor Stinnerb744ba12010-05-15 12:27:16 +0000723static void
724initfsencoding(void)
725{
726 PyObject *codec;
727#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000728 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000729
Victor Stinner7f84ab52010-06-11 00:36:33 +0000730 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000731 /* On Unix, set the file system encoding according to the
732 user's preference, if the CODESET names a well-known
733 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000734 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000735 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000736 if (codeset == NULL)
737 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000738
Victor Stinnere4743092010-10-19 00:05:51 +0000739 Py_FileSystemDefaultEncoding = codeset;
740 Py_HasFileSystemDefaultEncoding = 0;
741 return;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000742 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000743#endif
744
745 /* the encoding is mbcs, utf-8 or ascii */
746 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
747 if (!codec) {
748 /* Such error can only occurs in critical situations: no more
749 * memory, import a module of the standard library failed,
750 * etc. */
751 Py_FatalError("Py_Initialize: unable to load the file system codec");
752 } else {
753 Py_DECREF(codec);
754 }
755}
756
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000757/* Import the site module (not into __main__ though) */
758
759static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000760initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyObject *m;
763 m = PyImport_ImportModule("site");
764 if (m == NULL) {
765 PyErr_Print();
766 Py_Finalize();
767 exit(1);
768 }
769 else {
770 Py_DECREF(m);
771 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000772}
773
Antoine Pitrou05608432009-01-09 18:53:14 +0000774static PyObject*
775create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 int fd, int write_mode, char* name,
777 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
780 const char* mode;
781 PyObject *line_buffering;
782 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* stdin is always opened in buffered mode, first because it shouldn't
785 make a difference in common use cases, second because TextIOWrapper
786 depends on the presence of a read1() method which only exists on
787 buffered streams.
788 */
789 if (Py_UnbufferedStdioFlag && write_mode)
790 buffering = 0;
791 else
792 buffering = -1;
793 if (write_mode)
794 mode = "wb";
795 else
796 mode = "rb";
797 buf = PyObject_CallMethod(io, "open", "isiOOOi",
798 fd, mode, buffering,
799 Py_None, Py_None, Py_None, 0);
800 if (buf == NULL)
801 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 if (buffering) {
804 raw = PyObject_GetAttrString(buf, "raw");
805 if (raw == NULL)
806 goto error;
807 }
808 else {
809 raw = buf;
810 Py_INCREF(raw);
811 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 text = PyUnicode_FromString(name);
814 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
815 goto error;
816 res = PyObject_CallMethod(raw, "isatty", "");
817 if (res == NULL)
818 goto error;
819 isatty = PyObject_IsTrue(res);
820 Py_DECREF(res);
821 if (isatty == -1)
822 goto error;
823 if (isatty || Py_UnbufferedStdioFlag)
824 line_buffering = Py_True;
825 else
826 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 Py_CLEAR(raw);
829 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
832 buf, encoding, errors,
833 "\n", line_buffering);
834 Py_CLEAR(buf);
835 if (stream == NULL)
836 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 if (write_mode)
839 mode = "w";
840 else
841 mode = "r";
842 text = PyUnicode_FromString(mode);
843 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
844 goto error;
845 Py_CLEAR(text);
846 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000847
848error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 Py_XDECREF(buf);
850 Py_XDECREF(stream);
851 Py_XDECREF(text);
852 Py_XDECREF(raw);
853 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000854}
855
Georg Brandl1a3284e2007-12-02 09:40:06 +0000856/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000857static int
858initstdio(void)
859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 PyObject *iomod = NULL, *wrapper;
861 PyObject *bimod = NULL;
862 PyObject *m;
863 PyObject *std = NULL;
864 int status = 0, fd;
865 PyObject * encoding_attr;
866 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 /* Hack to avoid a nasty recursion issue when Python is invoked
869 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
870 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
871 goto error;
872 }
873 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
876 goto error;
877 }
878 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 if (!(bimod = PyImport_ImportModule("builtins"))) {
881 goto error;
882 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (!(iomod = PyImport_ImportModule("io"))) {
885 goto error;
886 }
887 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
888 goto error;
889 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* Set builtins.open */
892 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000893 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 goto error;
895 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000896 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 encoding = Py_GETENV("PYTHONIOENCODING");
899 errors = NULL;
900 if (encoding) {
901 encoding = strdup(encoding);
902 errors = strchr(encoding, ':');
903 if (errors) {
904 *errors = '\0';
905 errors++;
906 }
907 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 /* Set sys.stdin */
910 fd = fileno(stdin);
911 /* Under some conditions stdin, stdout and stderr may not be connected
912 * and fileno() may point to an invalid file descriptor. For example
913 * GUI apps don't have valid standard streams by default.
914 */
915 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000916#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 std = Py_None;
918 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000919#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000921#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 }
923 else {
924 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
925 if (std == NULL)
926 goto error;
927 } /* if (fd < 0) */
928 PySys_SetObject("__stdin__", std);
929 PySys_SetObject("stdin", std);
930 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 /* Set sys.stdout */
933 fd = fileno(stdout);
934 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000935#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 std = Py_None;
937 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000938#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000940#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 }
942 else {
943 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
944 if (std == NULL)
945 goto error;
946 } /* if (fd < 0) */
947 PySys_SetObject("__stdout__", std);
948 PySys_SetObject("stdout", std);
949 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000950
Guido van Rossum98297ee2007-11-06 21:34:58 +0000951#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 /* Set sys.stderr, replaces the preliminary stderr */
953 fd = fileno(stderr);
954 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000955#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 std = Py_None;
957 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000958#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000960#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 }
962 else {
963 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
964 if (std == NULL)
965 goto error;
966 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* Same as hack above, pre-import stderr's codec to avoid recursion
969 when import.c tries to write to stderr in verbose mode. */
970 encoding_attr = PyObject_GetAttrString(std, "encoding");
971 if (encoding_attr != NULL) {
972 const char * encoding;
973 encoding = _PyUnicode_AsString(encoding_attr);
974 if (encoding != NULL) {
975 _PyCodec_Lookup(encoding);
976 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000977 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 }
979 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 PySys_SetObject("__stderr__", std);
982 PySys_SetObject("stderr", std);
983 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000984#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000987 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 status = -1;
989 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (encoding)
992 free(encoding);
993 Py_XDECREF(bimod);
994 Py_XDECREF(iomod);
995 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000996}
997
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000998/* Parse input from a file and execute it */
999
1000int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001001PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (filename == NULL)
1005 filename = "???";
1006 if (Py_FdIsInteractive(fp, filename)) {
1007 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1008 if (closeit)
1009 fclose(fp);
1010 return err;
1011 }
1012 else
1013 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001014}
1015
1016int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001017PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 PyObject *v;
1020 int ret;
1021 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (flags == NULL) {
1024 flags = &local_flags;
1025 local_flags.cf_flags = 0;
1026 }
1027 v = PySys_GetObject("ps1");
1028 if (v == NULL) {
1029 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1030 Py_XDECREF(v);
1031 }
1032 v = PySys_GetObject("ps2");
1033 if (v == NULL) {
1034 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1035 Py_XDECREF(v);
1036 }
1037 for (;;) {
1038 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1039 PRINT_TOTAL_REFS();
1040 if (ret == E_EOF)
1041 return 0;
1042 /*
1043 if (ret == E_NOMEM)
1044 return -1;
1045 */
1046 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001047}
1048
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001049/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001050static int PARSER_FLAGS(PyCompilerFlags *flags)
1051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 int parser_flags = 0;
1053 if (!flags)
1054 return 0;
1055 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1056 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1057 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1058 parser_flags |= PyPARSE_IGNORE_COOKIE;
1059 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1060 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1061 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001062}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001063
Thomas Wouters89f507f2006-12-13 04:49:30 +00001064#if 0
1065/* Keep an example of flags with future keyword support. */
1066#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1068 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1069 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1070 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001071#endif
1072
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001073int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001074PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 PyObject *m, *d, *v, *w, *oenc = NULL;
1077 mod_ty mod;
1078 PyArena *arena;
1079 char *ps1 = "", *ps2 = "", *enc = NULL;
1080 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 if (fp == stdin) {
1083 /* Fetch encoding from sys.stdin */
1084 v = PySys_GetObject("stdin");
1085 if (v == NULL || v == Py_None)
1086 return -1;
1087 oenc = PyObject_GetAttrString(v, "encoding");
1088 if (!oenc)
1089 return -1;
1090 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001091 if (enc == NULL)
1092 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 }
1094 v = PySys_GetObject("ps1");
1095 if (v != NULL) {
1096 v = PyObject_Str(v);
1097 if (v == NULL)
1098 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001099 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001101 if (ps1 == NULL) {
1102 PyErr_Clear();
1103 ps1 = "";
1104 }
1105 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 }
1107 w = PySys_GetObject("ps2");
1108 if (w != NULL) {
1109 w = PyObject_Str(w);
1110 if (w == NULL)
1111 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001112 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001114 if (ps2 == NULL) {
1115 PyErr_Clear();
1116 ps2 = "";
1117 }
1118 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 }
1120 arena = PyArena_New();
1121 if (arena == NULL) {
1122 Py_XDECREF(v);
1123 Py_XDECREF(w);
1124 Py_XDECREF(oenc);
1125 return -1;
1126 }
1127 mod = PyParser_ASTFromFile(fp, filename, enc,
1128 Py_single_input, ps1, ps2,
1129 flags, &errcode, arena);
1130 Py_XDECREF(v);
1131 Py_XDECREF(w);
1132 Py_XDECREF(oenc);
1133 if (mod == NULL) {
1134 PyArena_Free(arena);
1135 if (errcode == E_EOF) {
1136 PyErr_Clear();
1137 return E_EOF;
1138 }
1139 PyErr_Print();
1140 return -1;
1141 }
1142 m = PyImport_AddModule("__main__");
1143 if (m == NULL) {
1144 PyArena_Free(arena);
1145 return -1;
1146 }
1147 d = PyModule_GetDict(m);
1148 v = run_mod(mod, filename, d, d, flags, arena);
1149 PyArena_Free(arena);
1150 flush_io();
1151 if (v == NULL) {
1152 PyErr_Print();
1153 return -1;
1154 }
1155 Py_DECREF(v);
1156 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001157}
1158
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001159/* Check whether a file maybe a pyc file: Look at the extension,
1160 the file type, and, if we may close it, at the first few bytes. */
1161
1162static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001163maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1166 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 /* Only look into the file if we are allowed to close it, since
1169 it then should also be seekable. */
1170 if (closeit) {
1171 /* Read only two bytes of the magic. If the file was opened in
1172 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1173 be read as they are on disk. */
1174 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1175 unsigned char buf[2];
1176 /* Mess: In case of -x, the stream is NOT at its start now,
1177 and ungetc() was used to push back the first newline,
1178 which makes the current stream position formally undefined,
1179 and a x-platform nightmare.
1180 Unfortunately, we have no direct way to know whether -x
1181 was specified. So we use a terrible hack: if the current
1182 stream position is not 0, we assume -x was specified, and
1183 give up. Bug 132850 on SourceForge spells out the
1184 hopelessness of trying anything else (fseek and ftell
1185 don't work predictably x-platform for text-mode files).
1186 */
1187 int ispyc = 0;
1188 if (ftell(fp) == 0) {
1189 if (fread(buf, 1, 2, fp) == 2 &&
1190 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1191 ispyc = 1;
1192 rewind(fp);
1193 }
1194 return ispyc;
1195 }
1196 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001197}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001198
Guido van Rossum0df002c2000-08-27 19:21:52 +00001199int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001200PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 PyObject *m, *d, *v;
1204 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001205 int set_file_name = 0, ret;
1206 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 m = PyImport_AddModule("__main__");
1209 if (m == NULL)
1210 return -1;
1211 d = PyModule_GetDict(m);
1212 if (PyDict_GetItemString(d, "__file__") == NULL) {
1213 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001214 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 if (f == NULL)
1216 return -1;
1217 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1218 Py_DECREF(f);
1219 return -1;
1220 }
1221 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1222 return -1;
1223 set_file_name = 1;
1224 Py_DECREF(f);
1225 }
1226 len = strlen(filename);
1227 ext = filename + len - (len > 4 ? 4 : 0);
1228 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1229 /* Try to run a pyc file. First, re-open in binary */
1230 if (closeit)
1231 fclose(fp);
1232 if ((fp = fopen(filename, "rb")) == NULL) {
1233 fprintf(stderr, "python: Can't reopen .pyc file\n");
1234 ret = -1;
1235 goto done;
1236 }
1237 /* Turn on optimization if a .pyo file is given */
1238 if (strcmp(ext, ".pyo") == 0)
1239 Py_OptimizeFlag = 1;
1240 v = run_pyc_file(fp, filename, d, d, flags);
1241 } else {
1242 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1243 closeit, flags);
1244 }
1245 flush_io();
1246 if (v == NULL) {
1247 PyErr_Print();
1248 ret = -1;
1249 goto done;
1250 }
1251 Py_DECREF(v);
1252 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001253 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1255 PyErr_Clear();
1256 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001257}
1258
1259int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001260PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 PyObject *m, *d, *v;
1263 m = PyImport_AddModule("__main__");
1264 if (m == NULL)
1265 return -1;
1266 d = PyModule_GetDict(m);
1267 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1268 if (v == NULL) {
1269 PyErr_Print();
1270 return -1;
1271 }
1272 Py_DECREF(v);
1273 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001274}
1275
Barry Warsaw035574d1997-08-29 22:07:17 +00001276static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001277parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 long hold;
1281 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 /* old style errors */
1284 if (PyTuple_Check(err))
1285 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1286 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (! (v = PyObject_GetAttrString(err, "msg")))
1291 goto finally;
1292 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (!(v = PyObject_GetAttrString(err, "filename")))
1295 goto finally;
1296 if (v == Py_None)
1297 *filename = NULL;
1298 else if (! (*filename = _PyUnicode_AsString(v)))
1299 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 Py_DECREF(v);
1302 if (!(v = PyObject_GetAttrString(err, "lineno")))
1303 goto finally;
1304 hold = PyLong_AsLong(v);
1305 Py_DECREF(v);
1306 v = NULL;
1307 if (hold < 0 && PyErr_Occurred())
1308 goto finally;
1309 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 if (!(v = PyObject_GetAttrString(err, "offset")))
1312 goto finally;
1313 if (v == Py_None) {
1314 *offset = -1;
1315 Py_DECREF(v);
1316 v = NULL;
1317 } else {
1318 hold = PyLong_AsLong(v);
1319 Py_DECREF(v);
1320 v = NULL;
1321 if (hold < 0 && PyErr_Occurred())
1322 goto finally;
1323 *offset = (int)hold;
1324 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (!(v = PyObject_GetAttrString(err, "text")))
1327 goto finally;
1328 if (v == Py_None)
1329 *text = NULL;
1330 else if (!PyUnicode_Check(v) ||
1331 !(*text = _PyUnicode_AsString(v)))
1332 goto finally;
1333 Py_DECREF(v);
1334 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001335
1336finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 Py_XDECREF(v);
1338 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001339}
1340
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001341void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001342PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001345}
1346
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001347static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001348print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 char *nl;
1351 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001352 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1353 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 for (;;) {
1355 nl = strchr(text, '\n');
1356 if (nl == NULL || nl-text >= offset)
1357 break;
1358 offset -= (int)(nl+1-text);
1359 text = nl+1;
1360 }
1361 while (*text == ' ' || *text == '\t') {
1362 text++;
1363 offset--;
1364 }
1365 }
1366 PyFile_WriteString(" ", f);
1367 PyFile_WriteString(text, f);
1368 if (*text == '\0' || text[strlen(text)-1] != '\n')
1369 PyFile_WriteString("\n", f);
1370 if (offset == -1)
1371 return;
1372 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001373 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001376}
1377
Guido van Rossum66e8e862001-03-23 17:54:43 +00001378static void
1379handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 PyObject *exception, *value, *tb;
1382 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 if (Py_InspectFlag)
1385 /* Don't exit if -i flag was given. This flag is set to 0
1386 * when entering interactive mode for inspecting. */
1387 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyErr_Fetch(&exception, &value, &tb);
1390 fflush(stdout);
1391 if (value == NULL || value == Py_None)
1392 goto done;
1393 if (PyExceptionInstance_Check(value)) {
1394 /* The error code should be in the `code' attribute. */
1395 PyObject *code = PyObject_GetAttrString(value, "code");
1396 if (code) {
1397 Py_DECREF(value);
1398 value = code;
1399 if (value == Py_None)
1400 goto done;
1401 }
1402 /* If we failed to dig out the 'code' attribute,
1403 just let the else clause below print the error. */
1404 }
1405 if (PyLong_Check(value))
1406 exitcode = (int)PyLong_AsLong(value);
1407 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001408 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001409 if (sys_stderr != NULL && sys_stderr != Py_None) {
1410 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1411 } else {
1412 PyObject_Print(value, stderr, Py_PRINT_RAW);
1413 fflush(stderr);
1414 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 PySys_WriteStderr("\n");
1416 exitcode = 1;
1417 }
Tim Peterscf615b52003-04-19 18:47:02 +00001418 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 /* Restore and clear the exception info, in order to properly decref
1420 * the exception, value, and traceback. If we just exit instead,
1421 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1422 * some finalizers from running.
1423 */
1424 PyErr_Restore(exception, value, tb);
1425 PyErr_Clear();
1426 Py_Exit(exitcode);
1427 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001428}
1429
1430void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001431PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1436 handle_system_exit();
1437 }
1438 PyErr_Fetch(&exception, &v, &tb);
1439 if (exception == NULL)
1440 return;
1441 PyErr_NormalizeException(&exception, &v, &tb);
1442 if (tb == NULL) {
1443 tb = Py_None;
1444 Py_INCREF(tb);
1445 }
1446 PyException_SetTraceback(v, tb);
1447 if (exception == NULL)
1448 return;
1449 /* Now we know v != NULL too */
1450 if (set_sys_last_vars) {
1451 PySys_SetObject("last_type", exception);
1452 PySys_SetObject("last_value", v);
1453 PySys_SetObject("last_traceback", tb);
1454 }
1455 hook = PySys_GetObject("excepthook");
1456 if (hook) {
1457 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1458 PyObject *result = PyEval_CallObject(hook, args);
1459 if (result == NULL) {
1460 PyObject *exception2, *v2, *tb2;
1461 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1462 handle_system_exit();
1463 }
1464 PyErr_Fetch(&exception2, &v2, &tb2);
1465 PyErr_NormalizeException(&exception2, &v2, &tb2);
1466 /* It should not be possible for exception2 or v2
1467 to be NULL. However PyErr_Display() can't
1468 tolerate NULLs, so just be safe. */
1469 if (exception2 == NULL) {
1470 exception2 = Py_None;
1471 Py_INCREF(exception2);
1472 }
1473 if (v2 == NULL) {
1474 v2 = Py_None;
1475 Py_INCREF(v2);
1476 }
1477 fflush(stdout);
1478 PySys_WriteStderr("Error in sys.excepthook:\n");
1479 PyErr_Display(exception2, v2, tb2);
1480 PySys_WriteStderr("\nOriginal exception was:\n");
1481 PyErr_Display(exception, v, tb);
1482 Py_DECREF(exception2);
1483 Py_DECREF(v2);
1484 Py_XDECREF(tb2);
1485 }
1486 Py_XDECREF(result);
1487 Py_XDECREF(args);
1488 } else {
1489 PySys_WriteStderr("sys.excepthook is missing\n");
1490 PyErr_Display(exception, v, tb);
1491 }
1492 Py_XDECREF(exception);
1493 Py_XDECREF(v);
1494 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001495}
1496
Benjamin Petersone6528212008-07-15 15:32:09 +00001497static void
1498print_exception(PyObject *f, PyObject *value)
1499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 int err = 0;
1501 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 if (!PyExceptionInstance_Check(value)) {
1504 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1505 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1506 PyFile_WriteString(" found\n", f);
1507 return;
1508 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 Py_INCREF(value);
1511 fflush(stdout);
1512 type = (PyObject *) Py_TYPE(value);
1513 tb = PyException_GetTraceback(value);
1514 if (tb && tb != Py_None)
1515 err = PyTraceBack_Print(tb, f);
1516 if (err == 0 &&
1517 PyObject_HasAttrString(value, "print_file_and_line"))
1518 {
1519 PyObject *message;
1520 const char *filename, *text;
1521 int lineno, offset;
1522 if (!parse_syntax_error(value, &message, &filename,
1523 &lineno, &offset, &text))
1524 PyErr_Clear();
1525 else {
1526 char buf[10];
1527 PyFile_WriteString(" File \"", f);
1528 if (filename == NULL)
1529 PyFile_WriteString("<string>", f);
1530 else
1531 PyFile_WriteString(filename, f);
1532 PyFile_WriteString("\", line ", f);
1533 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1534 PyFile_WriteString(buf, f);
1535 PyFile_WriteString("\n", f);
1536 if (text != NULL)
1537 print_error_text(f, offset, text);
1538 Py_DECREF(value);
1539 value = message;
1540 /* Can't be bothered to check all those
1541 PyFile_WriteString() calls */
1542 if (PyErr_Occurred())
1543 err = -1;
1544 }
1545 }
1546 if (err) {
1547 /* Don't do anything else */
1548 }
1549 else {
1550 PyObject* moduleName;
1551 char* className;
1552 assert(PyExceptionClass_Check(type));
1553 className = PyExceptionClass_Name(type);
1554 if (className != NULL) {
1555 char *dot = strrchr(className, '.');
1556 if (dot != NULL)
1557 className = dot+1;
1558 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 moduleName = PyObject_GetAttrString(type, "__module__");
1561 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1562 {
1563 Py_DECREF(moduleName);
1564 err = PyFile_WriteString("<unknown>", f);
1565 }
1566 else {
1567 char* modstr = _PyUnicode_AsString(moduleName);
1568 if (modstr && strcmp(modstr, "builtins"))
1569 {
1570 err = PyFile_WriteString(modstr, f);
1571 err += PyFile_WriteString(".", f);
1572 }
1573 Py_DECREF(moduleName);
1574 }
1575 if (err == 0) {
1576 if (className == NULL)
1577 err = PyFile_WriteString("<unknown>", f);
1578 else
1579 err = PyFile_WriteString(className, f);
1580 }
1581 }
1582 if (err == 0 && (value != Py_None)) {
1583 PyObject *s = PyObject_Str(value);
1584 /* only print colon if the str() of the
1585 object is not the empty string
1586 */
1587 if (s == NULL)
1588 err = -1;
1589 else if (!PyUnicode_Check(s) ||
1590 PyUnicode_GetSize(s) != 0)
1591 err = PyFile_WriteString(": ", f);
1592 if (err == 0)
1593 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1594 Py_XDECREF(s);
1595 }
1596 /* try to write a newline in any case */
1597 err += PyFile_WriteString("\n", f);
1598 Py_XDECREF(tb);
1599 Py_DECREF(value);
1600 /* If an error happened here, don't show it.
1601 XXX This is wrong, but too many callers rely on this behavior. */
1602 if (err != 0)
1603 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001604}
1605
1606static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 "\nThe above exception was the direct cause "
1608 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001609
1610static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 "\nDuring handling of the above exception, "
1612 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001613
1614static void
1615print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 int err = 0, res;
1618 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 if (seen != NULL) {
1621 /* Exception chaining */
1622 if (PySet_Add(seen, value) == -1)
1623 PyErr_Clear();
1624 else if (PyExceptionInstance_Check(value)) {
1625 cause = PyException_GetCause(value);
1626 context = PyException_GetContext(value);
1627 if (cause) {
1628 res = PySet_Contains(seen, cause);
1629 if (res == -1)
1630 PyErr_Clear();
1631 if (res == 0) {
1632 print_exception_recursive(
1633 f, cause, seen);
1634 err |= PyFile_WriteString(
1635 cause_message, f);
1636 }
1637 }
1638 else if (context) {
1639 res = PySet_Contains(seen, context);
1640 if (res == -1)
1641 PyErr_Clear();
1642 if (res == 0) {
1643 print_exception_recursive(
1644 f, context, seen);
1645 err |= PyFile_WriteString(
1646 context_message, f);
1647 }
1648 }
1649 Py_XDECREF(context);
1650 Py_XDECREF(cause);
1651 }
1652 }
1653 print_exception(f, value);
1654 if (err != 0)
1655 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001656}
1657
Thomas Wouters477c8d52006-05-27 19:21:47 +00001658void
1659PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 PyObject *seen;
1662 PyObject *f = PySys_GetObject("stderr");
1663 if (f == Py_None) {
1664 /* pass */
1665 }
1666 else if (f == NULL) {
1667 _PyObject_Dump(value);
1668 fprintf(stderr, "lost sys.stderr\n");
1669 }
1670 else {
1671 /* We choose to ignore seen being possibly NULL, and report
1672 at least the main exception (it could be a MemoryError).
1673 */
1674 seen = PySet_New(NULL);
1675 if (seen == NULL)
1676 PyErr_Clear();
1677 print_exception_recursive(f, value, seen);
1678 Py_XDECREF(seen);
1679 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001680}
1681
Guido van Rossum82598051997-03-05 00:20:32 +00001682PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001683PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 PyObject *ret = NULL;
1687 mod_ty mod;
1688 PyArena *arena = PyArena_New();
1689 if (arena == NULL)
1690 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1693 if (mod != NULL)
1694 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1695 PyArena_Free(arena);
1696 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001697}
1698
1699PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001700PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 PyObject *ret;
1704 mod_ty mod;
1705 PyArena *arena = PyArena_New();
1706 if (arena == NULL)
1707 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1710 flags, NULL, arena);
1711 if (closeit)
1712 fclose(fp);
1713 if (mod == NULL) {
1714 PyArena_Free(arena);
1715 return NULL;
1716 }
1717 ret = run_mod(mod, filename, globals, locals, flags, arena);
1718 PyArena_Free(arena);
1719 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001720}
1721
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001722static void
1723flush_io(void)
1724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 PyObject *f, *r;
1726 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 /* Save the current exception */
1729 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 f = PySys_GetObject("stderr");
1732 if (f != NULL) {
1733 r = PyObject_CallMethod(f, "flush", "");
1734 if (r)
1735 Py_DECREF(r);
1736 else
1737 PyErr_Clear();
1738 }
1739 f = PySys_GetObject("stdout");
1740 if (f != NULL) {
1741 r = PyObject_CallMethod(f, "flush", "");
1742 if (r)
1743 Py_DECREF(r);
1744 else
1745 PyErr_Clear();
1746 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001749}
1750
Guido van Rossum82598051997-03-05 00:20:32 +00001751static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001752run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 PyCodeObject *co;
1756 PyObject *v;
1757 co = PyAST_Compile(mod, filename, flags, arena);
1758 if (co == NULL)
1759 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001760 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 Py_DECREF(co);
1762 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001763}
1764
Guido van Rossum82598051997-03-05 00:20:32 +00001765static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001766run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 PyCodeObject *co;
1770 PyObject *v;
1771 long magic;
1772 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 magic = PyMarshal_ReadLongFromFile(fp);
1775 if (magic != PyImport_GetMagicNumber()) {
1776 PyErr_SetString(PyExc_RuntimeError,
1777 "Bad magic number in .pyc file");
1778 return NULL;
1779 }
1780 (void) PyMarshal_ReadLongFromFile(fp);
1781 v = PyMarshal_ReadLastObjectFromFile(fp);
1782 fclose(fp);
1783 if (v == NULL || !PyCode_Check(v)) {
1784 Py_XDECREF(v);
1785 PyErr_SetString(PyExc_RuntimeError,
1786 "Bad code object in .pyc file");
1787 return NULL;
1788 }
1789 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001790 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 if (v && flags)
1792 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1793 Py_DECREF(co);
1794 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001795}
1796
Guido van Rossum82598051997-03-05 00:20:32 +00001797PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001798Py_CompileStringExFlags(const char *str, const char *filename, int start,
1799 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 PyCodeObject *co;
1802 mod_ty mod;
1803 PyArena *arena = PyArena_New();
1804 if (arena == NULL)
1805 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1808 if (mod == NULL) {
1809 PyArena_Free(arena);
1810 return NULL;
1811 }
1812 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1813 PyObject *result = PyAST_mod2obj(mod);
1814 PyArena_Free(arena);
1815 return result;
1816 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001817 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 PyArena_Free(arena);
1819 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001820}
1821
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001822/* For use in Py_LIMITED_API */
1823#undef Py_CompileString
1824PyObject *
1825PyCompileString(const char *str, const char *filename, int start)
1826{
1827 return Py_CompileStringFlags(str, filename, start, NULL);
1828}
1829
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001830struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001831Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 struct symtable *st;
1834 mod_ty mod;
1835 PyCompilerFlags flags;
1836 PyArena *arena = PyArena_New();
1837 if (arena == NULL)
1838 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 flags.cf_flags = 0;
1841 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1842 if (mod == NULL) {
1843 PyArena_Free(arena);
1844 return NULL;
1845 }
1846 st = PySymtable_Build(mod, filename, 0);
1847 PyArena_Free(arena);
1848 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001849}
1850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851/* Preferred access to parser is through AST. */
1852mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001853PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 mod_ty mod;
1857 PyCompilerFlags localflags;
1858 perrdetail err;
1859 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1862 &_PyParser_Grammar, start, &err,
1863 &iflags);
1864 if (flags == NULL) {
1865 localflags.cf_flags = 0;
1866 flags = &localflags;
1867 }
1868 if (n) {
1869 flags->cf_flags |= iflags & PyCF_MASK;
1870 mod = PyAST_FromNode(n, flags, filename, arena);
1871 PyNode_Free(n);
1872 return mod;
1873 }
1874 else {
1875 err_input(&err);
1876 return NULL;
1877 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878}
1879
1880mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001881PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 int start, char *ps1,
1883 char *ps2, PyCompilerFlags *flags, int *errcode,
1884 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 mod_ty mod;
1887 PyCompilerFlags localflags;
1888 perrdetail err;
1889 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1892 &_PyParser_Grammar,
1893 start, ps1, ps2, &err, &iflags);
1894 if (flags == NULL) {
1895 localflags.cf_flags = 0;
1896 flags = &localflags;
1897 }
1898 if (n) {
1899 flags->cf_flags |= iflags & PyCF_MASK;
1900 mod = PyAST_FromNode(n, flags, filename, arena);
1901 PyNode_Free(n);
1902 return mod;
1903 }
1904 else {
1905 err_input(&err);
1906 if (errcode)
1907 *errcode = err.error;
1908 return NULL;
1909 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910}
1911
Guido van Rossuma110aa61994-08-29 12:50:44 +00001912/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001913
Guido van Rossuma110aa61994-08-29 12:50:44 +00001914node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001915PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 perrdetail err;
1918 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1919 &_PyParser_Grammar,
1920 start, NULL, NULL, &err, flags);
1921 if (n == NULL)
1922 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001925}
1926
Guido van Rossuma110aa61994-08-29 12:50:44 +00001927/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001928
Guido van Rossuma110aa61994-08-29 12:50:44 +00001929node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001930PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 perrdetail err;
1933 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1934 start, &err, flags);
1935 if (n == NULL)
1936 err_input(&err);
1937 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001938}
1939
1940node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001941PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 perrdetail err;
1945 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1946 &_PyParser_Grammar, start, &err, flags);
1947 if (n == NULL)
1948 err_input(&err);
1949 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001950}
1951
1952node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001953PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001956}
1957
Guido van Rossum66ebd912003-04-17 16:02:26 +00001958/* May want to move a more generalized form of this to parsetok.c or
1959 even parser modules. */
1960
1961void
1962PyParser_SetError(perrdetail *err)
1963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001965}
1966
Guido van Rossuma110aa61994-08-29 12:50:44 +00001967/* Set the error appropriate to the given input error code (see errcode.h) */
1968
1969static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001970err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 PyObject *v, *w, *errtype, *errtext;
1973 PyObject *msg_obj = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001974 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 errtype = PyExc_SyntaxError;
1978 switch (err->error) {
1979 case E_ERROR:
1980 return;
1981 case E_SYNTAX:
1982 errtype = PyExc_IndentationError;
1983 if (err->expected == INDENT)
1984 msg = "expected an indented block";
1985 else if (err->token == INDENT)
1986 msg = "unexpected indent";
1987 else if (err->token == DEDENT)
1988 msg = "unexpected unindent";
1989 else {
1990 errtype = PyExc_SyntaxError;
1991 msg = "invalid syntax";
1992 }
1993 break;
1994 case E_TOKEN:
1995 msg = "invalid token";
1996 break;
1997 case E_EOFS:
1998 msg = "EOF while scanning triple-quoted string literal";
1999 break;
2000 case E_EOLS:
2001 msg = "EOL while scanning string literal";
2002 break;
2003 case E_INTR:
2004 if (!PyErr_Occurred())
2005 PyErr_SetNone(PyExc_KeyboardInterrupt);
2006 goto cleanup;
2007 case E_NOMEM:
2008 PyErr_NoMemory();
2009 goto cleanup;
2010 case E_EOF:
2011 msg = "unexpected EOF while parsing";
2012 break;
2013 case E_TABSPACE:
2014 errtype = PyExc_TabError;
2015 msg = "inconsistent use of tabs and spaces in indentation";
2016 break;
2017 case E_OVERFLOW:
2018 msg = "expression too long";
2019 break;
2020 case E_DEDENT:
2021 errtype = PyExc_IndentationError;
2022 msg = "unindent does not match any outer indentation level";
2023 break;
2024 case E_TOODEEP:
2025 errtype = PyExc_IndentationError;
2026 msg = "too many levels of indentation";
2027 break;
2028 case E_DECODE: {
2029 PyObject *type, *value, *tb;
2030 PyErr_Fetch(&type, &value, &tb);
2031 msg = "unknown decode error";
2032 if (value != NULL)
2033 msg_obj = PyObject_Str(value);
2034 Py_XDECREF(type);
2035 Py_XDECREF(value);
2036 Py_XDECREF(tb);
2037 break;
2038 }
2039 case E_LINECONT:
2040 msg = "unexpected character after line continuation character";
2041 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 case E_IDENTIFIER:
2044 msg = "invalid character in identifier";
2045 break;
2046 default:
2047 fprintf(stderr, "error=%d\n", err->error);
2048 msg = "unknown parsing error";
2049 break;
2050 }
2051 /* err->text may not be UTF-8 in case of decoding errors.
2052 Explicitly convert to an object. */
2053 if (!err->text) {
2054 errtext = Py_None;
2055 Py_INCREF(Py_None);
2056 } else {
2057 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2058 "replace");
2059 }
Victor Stinner2f2ed1f2010-10-16 13:42:53 +00002060 if (err->filename != NULL)
2061 filename = PyUnicode_DecodeFSDefault(err->filename);
2062 else {
2063 Py_INCREF(Py_None);
2064 filename = Py_None;
2065 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002066 if (filename != NULL)
2067 v = Py_BuildValue("(NiiN)", filename,
2068 err->lineno, err->offset, errtext);
2069 else
2070 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 if (v != NULL) {
2072 if (msg_obj)
2073 w = Py_BuildValue("(OO)", msg_obj, v);
2074 else
2075 w = Py_BuildValue("(sO)", msg, v);
2076 } else
2077 w = NULL;
2078 Py_XDECREF(v);
2079 PyErr_SetObject(errtype, w);
2080 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002081cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 Py_XDECREF(msg_obj);
2083 if (err->text != NULL) {
2084 PyObject_FREE(err->text);
2085 err->text = NULL;
2086 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002087}
2088
2089/* Print fatal error message and abort */
2090
2091void
Tim Peters7c321a82002-07-09 02:57:01 +00002092Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 fprintf(stderr, "Fatal Python error: %s\n", msg);
2095 fflush(stderr); /* it helps in Windows debug build */
2096 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002097 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002099#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 {
2101 size_t len = strlen(msg);
2102 WCHAR* buffer;
2103 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 /* Convert the message to wchar_t. This uses a simple one-to-one
2106 conversion, assuming that the this error message actually uses ASCII
2107 only. If this ceases to be true, we will have to convert. */
2108 buffer = alloca( (len+1) * (sizeof *buffer));
2109 for( i=0; i<=len; ++i)
2110 buffer[i] = msg[i];
2111 OutputDebugStringW(L"Fatal Python error: ");
2112 OutputDebugStringW(buffer);
2113 OutputDebugStringW(L"\n");
2114 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002115#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002117#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002118#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002120}
2121
2122/* Clean up and exit */
2123
Guido van Rossuma110aa61994-08-29 12:50:44 +00002124#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002125#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002126#endif
2127
Collin Winter670e6922007-03-21 02:57:17 +00002128static void (*pyexitfunc)(void) = NULL;
2129/* For the atexit module. */
2130void _Py_PyAtExit(void (*func)(void))
2131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002133}
2134
2135static void
2136call_py_exitfuncs(void)
2137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (pyexitfunc == NULL)
2139 return;
Collin Winter670e6922007-03-21 02:57:17 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 (*pyexitfunc)();
2142 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002143}
2144
Antoine Pitrou011bd622009-10-20 21:52:47 +00002145/* Wait until threading._shutdown completes, provided
2146 the threading module was imported in the first place.
2147 The shutdown routine will wait until all non-daemon
2148 "threading" threads have completed. */
2149static void
2150wait_for_thread_shutdown(void)
2151{
2152#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 PyObject *result;
2154 PyThreadState *tstate = PyThreadState_GET();
2155 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2156 "threading");
2157 if (threading == NULL) {
2158 /* threading not imported */
2159 PyErr_Clear();
2160 return;
2161 }
2162 result = PyObject_CallMethod(threading, "_shutdown", "");
2163 if (result == NULL) {
2164 PyErr_WriteUnraisable(threading);
2165 }
2166 else {
2167 Py_DECREF(result);
2168 }
2169 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002170#endif
2171}
2172
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002173#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002174static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002175static int nexitfuncs = 0;
2176
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002177int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 if (nexitfuncs >= NEXITFUNCS)
2180 return -1;
2181 exitfuncs[nexitfuncs++] = func;
2182 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002183}
2184
Guido van Rossumcc283f51997-08-05 02:22:03 +00002185static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002186call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 while (nexitfuncs > 0)
2189 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 fflush(stdout);
2192 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002193}
2194
2195void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002196Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002201}
2202
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002203static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002204initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002205{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002206#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002208#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002209#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002211#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002212#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002214#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002216}
2217
Guido van Rossum7433b121997-02-14 19:45:36 +00002218
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002219/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2220 *
2221 * All of the code in this function must only use async-signal-safe functions,
2222 * listed at `man 7 signal` or
2223 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2224 */
2225void
2226_Py_RestoreSignals(void)
2227{
2228#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002230#endif
2231#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002233#endif
2234#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002236#endif
2237}
2238
2239
Guido van Rossum7433b121997-02-14 19:45:36 +00002240/*
2241 * The file descriptor fd is considered ``interactive'' if either
2242 * a) isatty(fd) is TRUE, or
2243 * b) the -i flag was given, and the filename associated with
2244 * the descriptor is NULL or "<stdin>" or "???".
2245 */
2246int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002247Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 if (isatty((int)fileno(fp)))
2250 return 1;
2251 if (!Py_InteractiveFlag)
2252 return 0;
2253 return (filename == NULL) ||
2254 (strcmp(filename, "<stdin>") == 0) ||
2255 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002256}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002257
2258
Tim Petersd08e3822003-04-17 15:24:21 +00002259#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002260#if defined(WIN32) && defined(_MSC_VER)
2261
2262/* Stack checking for Microsoft C */
2263
2264#include <malloc.h>
2265#include <excpt.h>
2266
Fred Drakee8de31c2000-08-31 05:38:39 +00002267/*
2268 * Return non-zero when we run out of memory on the stack; zero otherwise.
2269 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002270int
Fred Drake399739f2000-08-31 05:52:44 +00002271PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 __try {
2274 /* alloca throws a stack overflow exception if there's
2275 not enough space left on the stack */
2276 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2277 return 0;
2278 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2279 EXCEPTION_EXECUTE_HANDLER :
2280 EXCEPTION_CONTINUE_SEARCH) {
2281 int errcode = _resetstkoflw();
2282 if (errcode == 0)
2283 {
2284 Py_FatalError("Could not reset the stack!");
2285 }
2286 }
2287 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002288}
2289
2290#endif /* WIN32 && _MSC_VER */
2291
2292/* Alternate implementations can be added here... */
2293
2294#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002295
2296
2297/* Wrappers around sigaction() or signal(). */
2298
2299PyOS_sighandler_t
2300PyOS_getsig(int sig)
2301{
2302#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 struct sigaction context;
2304 if (sigaction(sig, NULL, &context) == -1)
2305 return SIG_ERR;
2306 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002307#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002309/* Special signal handling for the secure CRT in Visual Studio 2005 */
2310#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 switch (sig) {
2312 /* Only these signals are valid */
2313 case SIGINT:
2314 case SIGILL:
2315 case SIGFPE:
2316 case SIGSEGV:
2317 case SIGTERM:
2318 case SIGBREAK:
2319 case SIGABRT:
2320 break;
2321 /* Don't call signal() with other values or it will assert */
2322 default:
2323 return SIG_ERR;
2324 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002325#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 handler = signal(sig, SIG_IGN);
2327 if (handler != SIG_ERR)
2328 signal(sig, handler);
2329 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002330#endif
2331}
2332
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002333/*
2334 * All of the code in this function must only use async-signal-safe functions,
2335 * listed at `man 7 signal` or
2336 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2337 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002338PyOS_sighandler_t
2339PyOS_setsig(int sig, PyOS_sighandler_t handler)
2340{
2341#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 /* Some code in Modules/signalmodule.c depends on sigaction() being
2343 * used here if HAVE_SIGACTION is defined. Fix that if this code
2344 * changes to invalidate that assumption.
2345 */
2346 struct sigaction context, ocontext;
2347 context.sa_handler = handler;
2348 sigemptyset(&context.sa_mask);
2349 context.sa_flags = 0;
2350 if (sigaction(sig, &context, &ocontext) == -1)
2351 return SIG_ERR;
2352 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002353#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 PyOS_sighandler_t oldhandler;
2355 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002356#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002358#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002360#endif
2361}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002362
2363/* Deprecated C API functions still provided for binary compatiblity */
2364
2365#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002366PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002367PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370}
2371
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002372#undef PyParser_SimpleParseString
2373PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002374PyParser_SimpleParseString(const char *str, int start)
2375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002377}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002378
2379#undef PyRun_AnyFile
2380PyAPI_FUNC(int)
2381PyRun_AnyFile(FILE *fp, const char *name)
2382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002384}
2385
2386#undef PyRun_AnyFileEx
2387PyAPI_FUNC(int)
2388PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002391}
2392
2393#undef PyRun_AnyFileFlags
2394PyAPI_FUNC(int)
2395PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002398}
2399
2400#undef PyRun_File
2401PyAPI_FUNC(PyObject *)
2402PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002405}
2406
2407#undef PyRun_FileEx
2408PyAPI_FUNC(PyObject *)
2409PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002412}
2413
2414#undef PyRun_FileFlags
2415PyAPI_FUNC(PyObject *)
2416PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002420}
2421
2422#undef PyRun_SimpleFile
2423PyAPI_FUNC(int)
2424PyRun_SimpleFile(FILE *f, const char *p)
2425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002427}
2428
2429#undef PyRun_SimpleFileEx
2430PyAPI_FUNC(int)
2431PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002434}
2435
2436
2437#undef PyRun_String
2438PyAPI_FUNC(PyObject *)
2439PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002442}
2443
2444#undef PyRun_SimpleString
2445PyAPI_FUNC(int)
2446PyRun_SimpleString(const char *s)
2447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002449}
2450
2451#undef Py_CompileString
2452PyAPI_FUNC(PyObject *)
2453Py_CompileString(const char *str, const char *p, int s)
2454{
Georg Brandl8334fd92010-12-04 10:26:46 +00002455 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2456}
2457
2458#undef Py_CompileStringFlags
2459PyAPI_FUNC(PyObject *)
2460Py_CompileStringFlags(const char *str, const char *p, int s,
2461 PyCompilerFlags *flags)
2462{
2463 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002464}
2465
2466#undef PyRun_InteractiveOne
2467PyAPI_FUNC(int)
2468PyRun_InteractiveOne(FILE *f, const char *p)
2469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002471}
2472
2473#undef PyRun_InteractiveLoop
2474PyAPI_FUNC(int)
2475PyRun_InteractiveLoop(FILE *f, const char *p)
2476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002478}
2479
2480#ifdef __cplusplus
2481}
2482#endif