blob: e3836b8b7c8eabdd6fb8c584e440fb2122eb675c [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;
1205 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 m = PyImport_AddModule("__main__");
1208 if (m == NULL)
1209 return -1;
1210 d = PyModule_GetDict(m);
1211 if (PyDict_GetItemString(d, "__file__") == NULL) {
1212 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001213 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 if (f == NULL)
1215 return -1;
1216 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1217 Py_DECREF(f);
1218 return -1;
1219 }
1220 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1221 return -1;
1222 set_file_name = 1;
1223 Py_DECREF(f);
1224 }
1225 len = strlen(filename);
1226 ext = filename + len - (len > 4 ? 4 : 0);
1227 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1228 /* Try to run a pyc file. First, re-open in binary */
1229 if (closeit)
1230 fclose(fp);
1231 if ((fp = fopen(filename, "rb")) == NULL) {
1232 fprintf(stderr, "python: Can't reopen .pyc file\n");
1233 ret = -1;
1234 goto done;
1235 }
1236 /* Turn on optimization if a .pyo file is given */
1237 if (strcmp(ext, ".pyo") == 0)
1238 Py_OptimizeFlag = 1;
1239 v = run_pyc_file(fp, filename, d, d, flags);
1240 } else {
1241 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1242 closeit, flags);
1243 }
1244 flush_io();
1245 if (v == NULL) {
1246 PyErr_Print();
1247 ret = -1;
1248 goto done;
1249 }
1250 Py_DECREF(v);
1251 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001252 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1254 PyErr_Clear();
1255 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001256}
1257
1258int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001259PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 PyObject *m, *d, *v;
1262 m = PyImport_AddModule("__main__");
1263 if (m == NULL)
1264 return -1;
1265 d = PyModule_GetDict(m);
1266 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1267 if (v == NULL) {
1268 PyErr_Print();
1269 return -1;
1270 }
1271 Py_DECREF(v);
1272 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001273}
1274
Barry Warsaw035574d1997-08-29 22:07:17 +00001275static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001276parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 long hold;
1280 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 /* old style errors */
1283 if (PyTuple_Check(err))
1284 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1285 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (! (v = PyObject_GetAttrString(err, "msg")))
1290 goto finally;
1291 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (!(v = PyObject_GetAttrString(err, "filename")))
1294 goto finally;
1295 if (v == Py_None)
1296 *filename = NULL;
1297 else if (! (*filename = _PyUnicode_AsString(v)))
1298 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 Py_DECREF(v);
1301 if (!(v = PyObject_GetAttrString(err, "lineno")))
1302 goto finally;
1303 hold = PyLong_AsLong(v);
1304 Py_DECREF(v);
1305 v = NULL;
1306 if (hold < 0 && PyErr_Occurred())
1307 goto finally;
1308 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (!(v = PyObject_GetAttrString(err, "offset")))
1311 goto finally;
1312 if (v == Py_None) {
1313 *offset = -1;
1314 Py_DECREF(v);
1315 v = NULL;
1316 } else {
1317 hold = PyLong_AsLong(v);
1318 Py_DECREF(v);
1319 v = NULL;
1320 if (hold < 0 && PyErr_Occurred())
1321 goto finally;
1322 *offset = (int)hold;
1323 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (!(v = PyObject_GetAttrString(err, "text")))
1326 goto finally;
1327 if (v == Py_None)
1328 *text = NULL;
1329 else if (!PyUnicode_Check(v) ||
1330 !(*text = _PyUnicode_AsString(v)))
1331 goto finally;
1332 Py_DECREF(v);
1333 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001334
1335finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 Py_XDECREF(v);
1337 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001338}
1339
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001340void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001341PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001344}
1345
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001346static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001347print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 char *nl;
1350 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001351 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1352 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 for (;;) {
1354 nl = strchr(text, '\n');
1355 if (nl == NULL || nl-text >= offset)
1356 break;
1357 offset -= (int)(nl+1-text);
1358 text = nl+1;
1359 }
1360 while (*text == ' ' || *text == '\t') {
1361 text++;
1362 offset--;
1363 }
1364 }
1365 PyFile_WriteString(" ", f);
1366 PyFile_WriteString(text, f);
1367 if (*text == '\0' || text[strlen(text)-1] != '\n')
1368 PyFile_WriteString("\n", f);
1369 if (offset == -1)
1370 return;
1371 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001372 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001375}
1376
Guido van Rossum66e8e862001-03-23 17:54:43 +00001377static void
1378handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 PyObject *exception, *value, *tb;
1381 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 if (Py_InspectFlag)
1384 /* Don't exit if -i flag was given. This flag is set to 0
1385 * when entering interactive mode for inspecting. */
1386 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 PyErr_Fetch(&exception, &value, &tb);
1389 fflush(stdout);
1390 if (value == NULL || value == Py_None)
1391 goto done;
1392 if (PyExceptionInstance_Check(value)) {
1393 /* The error code should be in the `code' attribute. */
1394 PyObject *code = PyObject_GetAttrString(value, "code");
1395 if (code) {
1396 Py_DECREF(value);
1397 value = code;
1398 if (value == Py_None)
1399 goto done;
1400 }
1401 /* If we failed to dig out the 'code' attribute,
1402 just let the else clause below print the error. */
1403 }
1404 if (PyLong_Check(value))
1405 exitcode = (int)PyLong_AsLong(value);
1406 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001407 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001408 if (sys_stderr != NULL && sys_stderr != Py_None) {
1409 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1410 } else {
1411 PyObject_Print(value, stderr, Py_PRINT_RAW);
1412 fflush(stderr);
1413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 PySys_WriteStderr("\n");
1415 exitcode = 1;
1416 }
Tim Peterscf615b52003-04-19 18:47:02 +00001417 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 /* Restore and clear the exception info, in order to properly decref
1419 * the exception, value, and traceback. If we just exit instead,
1420 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1421 * some finalizers from running.
1422 */
1423 PyErr_Restore(exception, value, tb);
1424 PyErr_Clear();
1425 Py_Exit(exitcode);
1426 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001427}
1428
1429void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001430PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1435 handle_system_exit();
1436 }
1437 PyErr_Fetch(&exception, &v, &tb);
1438 if (exception == NULL)
1439 return;
1440 PyErr_NormalizeException(&exception, &v, &tb);
1441 if (tb == NULL) {
1442 tb = Py_None;
1443 Py_INCREF(tb);
1444 }
1445 PyException_SetTraceback(v, tb);
1446 if (exception == NULL)
1447 return;
1448 /* Now we know v != NULL too */
1449 if (set_sys_last_vars) {
1450 PySys_SetObject("last_type", exception);
1451 PySys_SetObject("last_value", v);
1452 PySys_SetObject("last_traceback", tb);
1453 }
1454 hook = PySys_GetObject("excepthook");
1455 if (hook) {
1456 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1457 PyObject *result = PyEval_CallObject(hook, args);
1458 if (result == NULL) {
1459 PyObject *exception2, *v2, *tb2;
1460 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1461 handle_system_exit();
1462 }
1463 PyErr_Fetch(&exception2, &v2, &tb2);
1464 PyErr_NormalizeException(&exception2, &v2, &tb2);
1465 /* It should not be possible for exception2 or v2
1466 to be NULL. However PyErr_Display() can't
1467 tolerate NULLs, so just be safe. */
1468 if (exception2 == NULL) {
1469 exception2 = Py_None;
1470 Py_INCREF(exception2);
1471 }
1472 if (v2 == NULL) {
1473 v2 = Py_None;
1474 Py_INCREF(v2);
1475 }
1476 fflush(stdout);
1477 PySys_WriteStderr("Error in sys.excepthook:\n");
1478 PyErr_Display(exception2, v2, tb2);
1479 PySys_WriteStderr("\nOriginal exception was:\n");
1480 PyErr_Display(exception, v, tb);
1481 Py_DECREF(exception2);
1482 Py_DECREF(v2);
1483 Py_XDECREF(tb2);
1484 }
1485 Py_XDECREF(result);
1486 Py_XDECREF(args);
1487 } else {
1488 PySys_WriteStderr("sys.excepthook is missing\n");
1489 PyErr_Display(exception, v, tb);
1490 }
1491 Py_XDECREF(exception);
1492 Py_XDECREF(v);
1493 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001494}
1495
Benjamin Petersone6528212008-07-15 15:32:09 +00001496static void
1497print_exception(PyObject *f, PyObject *value)
1498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 int err = 0;
1500 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if (!PyExceptionInstance_Check(value)) {
1503 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1504 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1505 PyFile_WriteString(" found\n", f);
1506 return;
1507 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 Py_INCREF(value);
1510 fflush(stdout);
1511 type = (PyObject *) Py_TYPE(value);
1512 tb = PyException_GetTraceback(value);
1513 if (tb && tb != Py_None)
1514 err = PyTraceBack_Print(tb, f);
1515 if (err == 0 &&
1516 PyObject_HasAttrString(value, "print_file_and_line"))
1517 {
1518 PyObject *message;
1519 const char *filename, *text;
1520 int lineno, offset;
1521 if (!parse_syntax_error(value, &message, &filename,
1522 &lineno, &offset, &text))
1523 PyErr_Clear();
1524 else {
1525 char buf[10];
1526 PyFile_WriteString(" File \"", f);
1527 if (filename == NULL)
1528 PyFile_WriteString("<string>", f);
1529 else
1530 PyFile_WriteString(filename, f);
1531 PyFile_WriteString("\", line ", f);
1532 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1533 PyFile_WriteString(buf, f);
1534 PyFile_WriteString("\n", f);
1535 if (text != NULL)
1536 print_error_text(f, offset, text);
1537 Py_DECREF(value);
1538 value = message;
1539 /* Can't be bothered to check all those
1540 PyFile_WriteString() calls */
1541 if (PyErr_Occurred())
1542 err = -1;
1543 }
1544 }
1545 if (err) {
1546 /* Don't do anything else */
1547 }
1548 else {
1549 PyObject* moduleName;
1550 char* className;
1551 assert(PyExceptionClass_Check(type));
1552 className = PyExceptionClass_Name(type);
1553 if (className != NULL) {
1554 char *dot = strrchr(className, '.');
1555 if (dot != NULL)
1556 className = dot+1;
1557 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 moduleName = PyObject_GetAttrString(type, "__module__");
1560 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1561 {
1562 Py_DECREF(moduleName);
1563 err = PyFile_WriteString("<unknown>", f);
1564 }
1565 else {
1566 char* modstr = _PyUnicode_AsString(moduleName);
1567 if (modstr && strcmp(modstr, "builtins"))
1568 {
1569 err = PyFile_WriteString(modstr, f);
1570 err += PyFile_WriteString(".", f);
1571 }
1572 Py_DECREF(moduleName);
1573 }
1574 if (err == 0) {
1575 if (className == NULL)
1576 err = PyFile_WriteString("<unknown>", f);
1577 else
1578 err = PyFile_WriteString(className, f);
1579 }
1580 }
1581 if (err == 0 && (value != Py_None)) {
1582 PyObject *s = PyObject_Str(value);
1583 /* only print colon if the str() of the
1584 object is not the empty string
1585 */
1586 if (s == NULL)
1587 err = -1;
1588 else if (!PyUnicode_Check(s) ||
1589 PyUnicode_GetSize(s) != 0)
1590 err = PyFile_WriteString(": ", f);
1591 if (err == 0)
1592 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1593 Py_XDECREF(s);
1594 }
1595 /* try to write a newline in any case */
1596 err += PyFile_WriteString("\n", f);
1597 Py_XDECREF(tb);
1598 Py_DECREF(value);
1599 /* If an error happened here, don't show it.
1600 XXX This is wrong, but too many callers rely on this behavior. */
1601 if (err != 0)
1602 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001603}
1604
1605static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 "\nThe above exception was the direct cause "
1607 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001608
1609static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 "\nDuring handling of the above exception, "
1611 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001612
1613static void
1614print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 int err = 0, res;
1617 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 if (seen != NULL) {
1620 /* Exception chaining */
1621 if (PySet_Add(seen, value) == -1)
1622 PyErr_Clear();
1623 else if (PyExceptionInstance_Check(value)) {
1624 cause = PyException_GetCause(value);
1625 context = PyException_GetContext(value);
1626 if (cause) {
1627 res = PySet_Contains(seen, cause);
1628 if (res == -1)
1629 PyErr_Clear();
1630 if (res == 0) {
1631 print_exception_recursive(
1632 f, cause, seen);
1633 err |= PyFile_WriteString(
1634 cause_message, f);
1635 }
1636 }
1637 else if (context) {
1638 res = PySet_Contains(seen, context);
1639 if (res == -1)
1640 PyErr_Clear();
1641 if (res == 0) {
1642 print_exception_recursive(
1643 f, context, seen);
1644 err |= PyFile_WriteString(
1645 context_message, f);
1646 }
1647 }
1648 Py_XDECREF(context);
1649 Py_XDECREF(cause);
1650 }
1651 }
1652 print_exception(f, value);
1653 if (err != 0)
1654 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001655}
1656
Thomas Wouters477c8d52006-05-27 19:21:47 +00001657void
1658PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 PyObject *seen;
1661 PyObject *f = PySys_GetObject("stderr");
1662 if (f == Py_None) {
1663 /* pass */
1664 }
1665 else if (f == NULL) {
1666 _PyObject_Dump(value);
1667 fprintf(stderr, "lost sys.stderr\n");
1668 }
1669 else {
1670 /* We choose to ignore seen being possibly NULL, and report
1671 at least the main exception (it could be a MemoryError).
1672 */
1673 seen = PySet_New(NULL);
1674 if (seen == NULL)
1675 PyErr_Clear();
1676 print_exception_recursive(f, value, seen);
1677 Py_XDECREF(seen);
1678 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001679}
1680
Guido van Rossum82598051997-03-05 00:20:32 +00001681PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001682PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyObject *ret = NULL;
1686 mod_ty mod;
1687 PyArena *arena = PyArena_New();
1688 if (arena == NULL)
1689 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1692 if (mod != NULL)
1693 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1694 PyArena_Free(arena);
1695 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001696}
1697
1698PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001699PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 PyObject *ret;
1703 mod_ty mod;
1704 PyArena *arena = PyArena_New();
1705 if (arena == NULL)
1706 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1709 flags, NULL, arena);
1710 if (closeit)
1711 fclose(fp);
1712 if (mod == NULL) {
1713 PyArena_Free(arena);
1714 return NULL;
1715 }
1716 ret = run_mod(mod, filename, globals, locals, flags, arena);
1717 PyArena_Free(arena);
1718 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001719}
1720
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001721static void
1722flush_io(void)
1723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 PyObject *f, *r;
1725 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 /* Save the current exception */
1728 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 f = PySys_GetObject("stderr");
1731 if (f != NULL) {
1732 r = PyObject_CallMethod(f, "flush", "");
1733 if (r)
1734 Py_DECREF(r);
1735 else
1736 PyErr_Clear();
1737 }
1738 f = PySys_GetObject("stdout");
1739 if (f != NULL) {
1740 r = PyObject_CallMethod(f, "flush", "");
1741 if (r)
1742 Py_DECREF(r);
1743 else
1744 PyErr_Clear();
1745 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001748}
1749
Guido van Rossum82598051997-03-05 00:20:32 +00001750static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001751run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PyCodeObject *co;
1755 PyObject *v;
1756 co = PyAST_Compile(mod, filename, flags, arena);
1757 if (co == NULL)
1758 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001759 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 Py_DECREF(co);
1761 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001762}
1763
Guido van Rossum82598051997-03-05 00:20:32 +00001764static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001765run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 PyCodeObject *co;
1769 PyObject *v;
1770 long magic;
1771 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 magic = PyMarshal_ReadLongFromFile(fp);
1774 if (magic != PyImport_GetMagicNumber()) {
1775 PyErr_SetString(PyExc_RuntimeError,
1776 "Bad magic number in .pyc file");
1777 return NULL;
1778 }
1779 (void) PyMarshal_ReadLongFromFile(fp);
1780 v = PyMarshal_ReadLastObjectFromFile(fp);
1781 fclose(fp);
1782 if (v == NULL || !PyCode_Check(v)) {
1783 Py_XDECREF(v);
1784 PyErr_SetString(PyExc_RuntimeError,
1785 "Bad code object in .pyc file");
1786 return NULL;
1787 }
1788 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001789 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 if (v && flags)
1791 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1792 Py_DECREF(co);
1793 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001794}
1795
Guido van Rossum82598051997-03-05 00:20:32 +00001796PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001797Py_CompileStringExFlags(const char *str, const char *filename, int start,
1798 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 PyCodeObject *co;
1801 mod_ty mod;
1802 PyArena *arena = PyArena_New();
1803 if (arena == NULL)
1804 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1807 if (mod == NULL) {
1808 PyArena_Free(arena);
1809 return NULL;
1810 }
1811 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1812 PyObject *result = PyAST_mod2obj(mod);
1813 PyArena_Free(arena);
1814 return result;
1815 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001816 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 PyArena_Free(arena);
1818 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001819}
1820
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001821/* For use in Py_LIMITED_API */
1822#undef Py_CompileString
1823PyObject *
1824PyCompileString(const char *str, const char *filename, int start)
1825{
1826 return Py_CompileStringFlags(str, filename, start, NULL);
1827}
1828
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001829struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001830Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 struct symtable *st;
1833 mod_ty mod;
1834 PyCompilerFlags flags;
1835 PyArena *arena = PyArena_New();
1836 if (arena == NULL)
1837 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 flags.cf_flags = 0;
1840 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1841 if (mod == NULL) {
1842 PyArena_Free(arena);
1843 return NULL;
1844 }
1845 st = PySymtable_Build(mod, filename, 0);
1846 PyArena_Free(arena);
1847 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001848}
1849
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001850/* Preferred access to parser is through AST. */
1851mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001852PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 mod_ty mod;
1856 PyCompilerFlags localflags;
1857 perrdetail err;
1858 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1861 &_PyParser_Grammar, start, &err,
1862 &iflags);
1863 if (flags == NULL) {
1864 localflags.cf_flags = 0;
1865 flags = &localflags;
1866 }
1867 if (n) {
1868 flags->cf_flags |= iflags & PyCF_MASK;
1869 mod = PyAST_FromNode(n, flags, filename, arena);
1870 PyNode_Free(n);
1871 return mod;
1872 }
1873 else {
1874 err_input(&err);
1875 return NULL;
1876 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001877}
1878
1879mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001880PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 int start, char *ps1,
1882 char *ps2, PyCompilerFlags *flags, int *errcode,
1883 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 mod_ty mod;
1886 PyCompilerFlags localflags;
1887 perrdetail err;
1888 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1891 &_PyParser_Grammar,
1892 start, ps1, ps2, &err, &iflags);
1893 if (flags == NULL) {
1894 localflags.cf_flags = 0;
1895 flags = &localflags;
1896 }
1897 if (n) {
1898 flags->cf_flags |= iflags & PyCF_MASK;
1899 mod = PyAST_FromNode(n, flags, filename, arena);
1900 PyNode_Free(n);
1901 return mod;
1902 }
1903 else {
1904 err_input(&err);
1905 if (errcode)
1906 *errcode = err.error;
1907 return NULL;
1908 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909}
1910
Guido van Rossuma110aa61994-08-29 12:50:44 +00001911/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001912
Guido van Rossuma110aa61994-08-29 12:50:44 +00001913node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001914PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 perrdetail err;
1917 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1918 &_PyParser_Grammar,
1919 start, NULL, NULL, &err, flags);
1920 if (n == NULL)
1921 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001924}
1925
Guido van Rossuma110aa61994-08-29 12:50:44 +00001926/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001927
Guido van Rossuma110aa61994-08-29 12:50:44 +00001928node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001929PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 perrdetail err;
1932 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1933 start, &err, flags);
1934 if (n == NULL)
1935 err_input(&err);
1936 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001937}
1938
1939node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001940PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 perrdetail err;
1944 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1945 &_PyParser_Grammar, start, &err, flags);
1946 if (n == NULL)
1947 err_input(&err);
1948 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001949}
1950
1951node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001952PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001955}
1956
Guido van Rossum66ebd912003-04-17 16:02:26 +00001957/* May want to move a more generalized form of this to parsetok.c or
1958 even parser modules. */
1959
1960void
1961PyParser_SetError(perrdetail *err)
1962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001964}
1965
Guido van Rossuma110aa61994-08-29 12:50:44 +00001966/* Set the error appropriate to the given input error code (see errcode.h) */
1967
1968static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001969err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 PyObject *v, *w, *errtype, *errtext;
1972 PyObject *msg_obj = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001973 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 errtype = PyExc_SyntaxError;
1977 switch (err->error) {
1978 case E_ERROR:
1979 return;
1980 case E_SYNTAX:
1981 errtype = PyExc_IndentationError;
1982 if (err->expected == INDENT)
1983 msg = "expected an indented block";
1984 else if (err->token == INDENT)
1985 msg = "unexpected indent";
1986 else if (err->token == DEDENT)
1987 msg = "unexpected unindent";
1988 else {
1989 errtype = PyExc_SyntaxError;
1990 msg = "invalid syntax";
1991 }
1992 break;
1993 case E_TOKEN:
1994 msg = "invalid token";
1995 break;
1996 case E_EOFS:
1997 msg = "EOF while scanning triple-quoted string literal";
1998 break;
1999 case E_EOLS:
2000 msg = "EOL while scanning string literal";
2001 break;
2002 case E_INTR:
2003 if (!PyErr_Occurred())
2004 PyErr_SetNone(PyExc_KeyboardInterrupt);
2005 goto cleanup;
2006 case E_NOMEM:
2007 PyErr_NoMemory();
2008 goto cleanup;
2009 case E_EOF:
2010 msg = "unexpected EOF while parsing";
2011 break;
2012 case E_TABSPACE:
2013 errtype = PyExc_TabError;
2014 msg = "inconsistent use of tabs and spaces in indentation";
2015 break;
2016 case E_OVERFLOW:
2017 msg = "expression too long";
2018 break;
2019 case E_DEDENT:
2020 errtype = PyExc_IndentationError;
2021 msg = "unindent does not match any outer indentation level";
2022 break;
2023 case E_TOODEEP:
2024 errtype = PyExc_IndentationError;
2025 msg = "too many levels of indentation";
2026 break;
2027 case E_DECODE: {
2028 PyObject *type, *value, *tb;
2029 PyErr_Fetch(&type, &value, &tb);
2030 msg = "unknown decode error";
2031 if (value != NULL)
2032 msg_obj = PyObject_Str(value);
2033 Py_XDECREF(type);
2034 Py_XDECREF(value);
2035 Py_XDECREF(tb);
2036 break;
2037 }
2038 case E_LINECONT:
2039 msg = "unexpected character after line continuation character";
2040 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 case E_IDENTIFIER:
2043 msg = "invalid character in identifier";
2044 break;
2045 default:
2046 fprintf(stderr, "error=%d\n", err->error);
2047 msg = "unknown parsing error";
2048 break;
2049 }
2050 /* err->text may not be UTF-8 in case of decoding errors.
2051 Explicitly convert to an object. */
2052 if (!err->text) {
2053 errtext = Py_None;
2054 Py_INCREF(Py_None);
2055 } else {
2056 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2057 "replace");
2058 }
Victor Stinner2f2ed1f2010-10-16 13:42:53 +00002059 if (err->filename != NULL)
2060 filename = PyUnicode_DecodeFSDefault(err->filename);
2061 else {
2062 Py_INCREF(Py_None);
2063 filename = Py_None;
2064 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002065 if (filename != NULL)
2066 v = Py_BuildValue("(NiiN)", filename,
2067 err->lineno, err->offset, errtext);
2068 else
2069 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (v != NULL) {
2071 if (msg_obj)
2072 w = Py_BuildValue("(OO)", msg_obj, v);
2073 else
2074 w = Py_BuildValue("(sO)", msg, v);
2075 } else
2076 w = NULL;
2077 Py_XDECREF(v);
2078 PyErr_SetObject(errtype, w);
2079 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002080cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 Py_XDECREF(msg_obj);
2082 if (err->text != NULL) {
2083 PyObject_FREE(err->text);
2084 err->text = NULL;
2085 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002086}
2087
2088/* Print fatal error message and abort */
2089
2090void
Tim Peters7c321a82002-07-09 02:57:01 +00002091Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 fprintf(stderr, "Fatal Python error: %s\n", msg);
2094 fflush(stderr); /* it helps in Windows debug build */
2095 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002096 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002098#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 {
2100 size_t len = strlen(msg);
2101 WCHAR* buffer;
2102 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 /* Convert the message to wchar_t. This uses a simple one-to-one
2105 conversion, assuming that the this error message actually uses ASCII
2106 only. If this ceases to be true, we will have to convert. */
2107 buffer = alloca( (len+1) * (sizeof *buffer));
2108 for( i=0; i<=len; ++i)
2109 buffer[i] = msg[i];
2110 OutputDebugStringW(L"Fatal Python error: ");
2111 OutputDebugStringW(buffer);
2112 OutputDebugStringW(L"\n");
2113 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002114#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002116#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002117#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002119}
2120
2121/* Clean up and exit */
2122
Guido van Rossuma110aa61994-08-29 12:50:44 +00002123#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002124#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002125#endif
2126
Collin Winter670e6922007-03-21 02:57:17 +00002127static void (*pyexitfunc)(void) = NULL;
2128/* For the atexit module. */
2129void _Py_PyAtExit(void (*func)(void))
2130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002132}
2133
2134static void
2135call_py_exitfuncs(void)
2136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (pyexitfunc == NULL)
2138 return;
Collin Winter670e6922007-03-21 02:57:17 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 (*pyexitfunc)();
2141 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002142}
2143
Antoine Pitrou011bd622009-10-20 21:52:47 +00002144/* Wait until threading._shutdown completes, provided
2145 the threading module was imported in the first place.
2146 The shutdown routine will wait until all non-daemon
2147 "threading" threads have completed. */
2148static void
2149wait_for_thread_shutdown(void)
2150{
2151#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyObject *result;
2153 PyThreadState *tstate = PyThreadState_GET();
2154 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2155 "threading");
2156 if (threading == NULL) {
2157 /* threading not imported */
2158 PyErr_Clear();
2159 return;
2160 }
2161 result = PyObject_CallMethod(threading, "_shutdown", "");
2162 if (result == NULL) {
2163 PyErr_WriteUnraisable(threading);
2164 }
2165 else {
2166 Py_DECREF(result);
2167 }
2168 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002169#endif
2170}
2171
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002172#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002173static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002174static int nexitfuncs = 0;
2175
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002176int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (nexitfuncs >= NEXITFUNCS)
2179 return -1;
2180 exitfuncs[nexitfuncs++] = func;
2181 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002182}
2183
Guido van Rossumcc283f51997-08-05 02:22:03 +00002184static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002185call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 while (nexitfuncs > 0)
2188 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 fflush(stdout);
2191 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002192}
2193
2194void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002195Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002200}
2201
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002202static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002203initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002204{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002205#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002207#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002208#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002210#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002211#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002213#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002215}
2216
Guido van Rossum7433b121997-02-14 19:45:36 +00002217
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002218/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2219 *
2220 * All of the code in this function must only use async-signal-safe functions,
2221 * listed at `man 7 signal` or
2222 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2223 */
2224void
2225_Py_RestoreSignals(void)
2226{
2227#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002229#endif
2230#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002232#endif
2233#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002235#endif
2236}
2237
2238
Guido van Rossum7433b121997-02-14 19:45:36 +00002239/*
2240 * The file descriptor fd is considered ``interactive'' if either
2241 * a) isatty(fd) is TRUE, or
2242 * b) the -i flag was given, and the filename associated with
2243 * the descriptor is NULL or "<stdin>" or "???".
2244 */
2245int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002246Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 if (isatty((int)fileno(fp)))
2249 return 1;
2250 if (!Py_InteractiveFlag)
2251 return 0;
2252 return (filename == NULL) ||
2253 (strcmp(filename, "<stdin>") == 0) ||
2254 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002255}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002256
2257
Tim Petersd08e3822003-04-17 15:24:21 +00002258#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002259#if defined(WIN32) && defined(_MSC_VER)
2260
2261/* Stack checking for Microsoft C */
2262
2263#include <malloc.h>
2264#include <excpt.h>
2265
Fred Drakee8de31c2000-08-31 05:38:39 +00002266/*
2267 * Return non-zero when we run out of memory on the stack; zero otherwise.
2268 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002269int
Fred Drake399739f2000-08-31 05:52:44 +00002270PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 __try {
2273 /* alloca throws a stack overflow exception if there's
2274 not enough space left on the stack */
2275 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2276 return 0;
2277 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2278 EXCEPTION_EXECUTE_HANDLER :
2279 EXCEPTION_CONTINUE_SEARCH) {
2280 int errcode = _resetstkoflw();
2281 if (errcode == 0)
2282 {
2283 Py_FatalError("Could not reset the stack!");
2284 }
2285 }
2286 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002287}
2288
2289#endif /* WIN32 && _MSC_VER */
2290
2291/* Alternate implementations can be added here... */
2292
2293#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002294
2295
2296/* Wrappers around sigaction() or signal(). */
2297
2298PyOS_sighandler_t
2299PyOS_getsig(int sig)
2300{
2301#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 struct sigaction context;
2303 if (sigaction(sig, NULL, &context) == -1)
2304 return SIG_ERR;
2305 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002306#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002308/* Special signal handling for the secure CRT in Visual Studio 2005 */
2309#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 switch (sig) {
2311 /* Only these signals are valid */
2312 case SIGINT:
2313 case SIGILL:
2314 case SIGFPE:
2315 case SIGSEGV:
2316 case SIGTERM:
2317 case SIGBREAK:
2318 case SIGABRT:
2319 break;
2320 /* Don't call signal() with other values or it will assert */
2321 default:
2322 return SIG_ERR;
2323 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002324#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 handler = signal(sig, SIG_IGN);
2326 if (handler != SIG_ERR)
2327 signal(sig, handler);
2328 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002329#endif
2330}
2331
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002332/*
2333 * All of the code in this function must only use async-signal-safe functions,
2334 * listed at `man 7 signal` or
2335 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2336 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002337PyOS_sighandler_t
2338PyOS_setsig(int sig, PyOS_sighandler_t handler)
2339{
2340#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 /* Some code in Modules/signalmodule.c depends on sigaction() being
2342 * used here if HAVE_SIGACTION is defined. Fix that if this code
2343 * changes to invalidate that assumption.
2344 */
2345 struct sigaction context, ocontext;
2346 context.sa_handler = handler;
2347 sigemptyset(&context.sa_mask);
2348 context.sa_flags = 0;
2349 if (sigaction(sig, &context, &ocontext) == -1)
2350 return SIG_ERR;
2351 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002352#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 PyOS_sighandler_t oldhandler;
2354 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002355#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002357#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002359#endif
2360}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361
2362/* Deprecated C API functions still provided for binary compatiblity */
2363
2364#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002365PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002366PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002369}
2370
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002371#undef PyParser_SimpleParseString
2372PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002373PyParser_SimpleParseString(const char *str, int start)
2374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002377
2378#undef PyRun_AnyFile
2379PyAPI_FUNC(int)
2380PyRun_AnyFile(FILE *fp, const char *name)
2381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002383}
2384
2385#undef PyRun_AnyFileEx
2386PyAPI_FUNC(int)
2387PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002390}
2391
2392#undef PyRun_AnyFileFlags
2393PyAPI_FUNC(int)
2394PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002397}
2398
2399#undef PyRun_File
2400PyAPI_FUNC(PyObject *)
2401PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002404}
2405
2406#undef PyRun_FileEx
2407PyAPI_FUNC(PyObject *)
2408PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002411}
2412
2413#undef PyRun_FileFlags
2414PyAPI_FUNC(PyObject *)
2415PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002419}
2420
2421#undef PyRun_SimpleFile
2422PyAPI_FUNC(int)
2423PyRun_SimpleFile(FILE *f, const char *p)
2424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002426}
2427
2428#undef PyRun_SimpleFileEx
2429PyAPI_FUNC(int)
2430PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002433}
2434
2435
2436#undef PyRun_String
2437PyAPI_FUNC(PyObject *)
2438PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002441}
2442
2443#undef PyRun_SimpleString
2444PyAPI_FUNC(int)
2445PyRun_SimpleString(const char *s)
2446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002448}
2449
2450#undef Py_CompileString
2451PyAPI_FUNC(PyObject *)
2452Py_CompileString(const char *str, const char *p, int s)
2453{
Georg Brandl8334fd92010-12-04 10:26:46 +00002454 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2455}
2456
2457#undef Py_CompileStringFlags
2458PyAPI_FUNC(PyObject *)
2459Py_CompileStringFlags(const char *str, const char *p, int s,
2460 PyCompilerFlags *flags)
2461{
2462 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002463}
2464
2465#undef PyRun_InteractiveOne
2466PyAPI_FUNC(int)
2467PyRun_InteractiveOne(FILE *f, const char *p)
2468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002470}
2471
2472#undef PyRun_InteractiveLoop
2473PyAPI_FUNC(int)
2474PyRun_InteractiveLoop(FILE *f, const char *p)
2475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002477}
2478
2479#ifdef __cplusplus
2480}
2481#endif