blob: 4b0ac139a2b0236950930722b7fef5079db108f5 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
43 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#endif
45
46#ifdef __cplusplus
47extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000048#endif
49
Martin v. Löwis790465f2008-04-05 20:41:37 +000050extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000051
Guido van Rossum82598051997-03-05 00:20:32 +000052extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossumb73cc041993-11-01 16:28:59 +000054/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static void initmain(void);
Victor Stinner3cbf14b2011-04-27 00:24:21 +020056static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
65static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000066static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000067static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000068static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000069extern void _PyUnicode_Init(void);
70extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000071extern int _PyLong_Init(void);
72extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000073
Mark Hammond8d98d2c2003-04-19 15:41:53 +000074#ifdef WITH_THREAD
75extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
76extern void _PyGILState_Fini(void);
77#endif /* WITH_THREAD */
78
Guido van Rossum82598051997-03-05 00:20:32 +000079int Py_DebugFlag; /* Needed by parser.c */
80int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000081int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000082int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020083int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
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
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020093PyThreadState *_Py_Finalizing = NULL;
94
Christian Heimes33fe8092008-04-13 13:53:33 +000095/* PyModule_GetWarningsModule is no longer necessary as of 2.6
96since _warnings is builtin. This API should not be used. */
97PyObject *
98PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000101}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000102
Guido van Rossum25ce5661997-08-02 03:10:38 +0000103static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000104
Thomas Wouters7e474022000-07-16 12:04:32 +0000105/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106
107int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000108Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111}
112
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113/* Global initializations. Can be undone by Py_Finalize(). Don't
114 call this twice without an intervening Py_Finalize() call. When
115 initializations fail, a fatal error is issued and the function does
116 not return. On return, the first thread and interpreter state have
117 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119 Locking: you must hold the interpreter lock while calling this.
120 (If the lock has not yet been initialized, that's equivalent to
121 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000125static int
126add_flag(int flag, const char *envs)
127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 int env = atoi(envs);
129 if (flag < env)
130 flag = env;
131 if (flag < 1)
132 flag = 1;
133 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000134}
135
Christian Heimes5833a2f2008-10-30 21:40:04 +0000136static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000137get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000138{
Victor Stinner94908bb2010-08-18 21:23:25 +0000139 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000140 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000141
Victor Stinner94908bb2010-08-18 21:23:25 +0000142 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 if (!codec)
144 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 name = PyObject_GetAttrString(codec, "name");
147 Py_CLEAR(codec);
148 if (!name)
149 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000150
Victor Stinner94908bb2010-08-18 21:23:25 +0000151 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner9c4efe52011-03-20 23:23:22 +0100152 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000153 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000154 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000156 if (name_str == NULL) {
157 PyErr_NoMemory();
158 return NULL;
159 }
160 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000161
162error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000164 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000166}
Victor Stinner94908bb2010-08-18 21:23:25 +0000167
168#if defined(HAVE_LANGINFO_H) && defined(CODESET)
169static char*
170get_codeset(void)
171{
172 char* codeset = nl_langinfo(CODESET);
173 if (!codeset || codeset[0] == '\0') {
174 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
175 return NULL;
176 }
177 return get_codec_name(codeset);
178}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000179#endif
180
Guido van Rossuma027efa1997-05-05 20:56:21 +0000181void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000182Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 PyInterpreterState *interp;
185 PyThreadState *tstate;
186 PyObject *bimod, *sysmod, *pstderr;
187 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (initialized)
191 return;
192 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200193 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000194
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000195#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Set up the LC_CTYPE locale, so we can obtain
197 the locale's charset without having to switch
198 locales. */
199 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000200#endif
201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
203 Py_DebugFlag = add_flag(Py_DebugFlag, p);
204 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
205 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
206 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
207 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
208 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
209 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 interp = PyInterpreterState_New();
212 if (interp == NULL)
213 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 tstate = PyThreadState_New(interp);
216 if (tstate == NULL)
217 Py_FatalError("Py_Initialize: can't make first thread");
218 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000219
Victor Stinner6961bd62010-08-17 22:26:51 +0000220#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000221 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
222 destroying the GIL might fail when it is being referenced from
223 another running thread (see issue #9901).
224 Instead we destroy the previously created GIL here, which ensures
225 that we can call Py_Initialize / Py_Finalize multiple times. */
226 _PyEval_FiniThreads();
227
228 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000229 _PyGILState_Init(interp, tstate);
230#endif /* WITH_THREAD */
231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (!_PyFrame_Init())
235 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (!_PyLong_Init())
238 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (!PyByteArray_Init())
241 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 interp->modules = PyDict_New();
246 if (interp->modules == NULL)
247 Py_FatalError("Py_Initialize: can't make modules dictionary");
248 interp->modules_reloading = PyDict_New();
249 if (interp->modules_reloading == NULL)
250 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 /* Init Unicode implementation; relies on the codec registry */
253 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 bimod = _PyBuiltin_Init();
256 if (bimod == NULL)
257 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000258 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 interp->builtins = PyModule_GetDict(bimod);
260 if (interp->builtins == NULL)
261 Py_FatalError("Py_Initialize: can't initialize builtins dict");
262 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 /* initialize builtin exceptions */
265 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 sysmod = _PySys_Init();
268 if (sysmod == NULL)
269 Py_FatalError("Py_Initialize: can't initialize sys");
270 interp->sysdict = PyModule_GetDict(sysmod);
271 if (interp->sysdict == NULL)
272 Py_FatalError("Py_Initialize: can't initialize sys dict");
273 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000274 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 PySys_SetPath(Py_GetPath());
276 PyDict_SetItemString(interp->sysdict, "modules",
277 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 /* Set up a preliminary stderr printer until we have enough
280 infrastructure for the io module in place. */
281 pstderr = PyFile_NewStdPrinter(fileno(stderr));
282 if (pstderr == NULL)
283 Py_FatalError("Py_Initialize: can't set preliminary stderr");
284 PySys_SetObject("stderr", pstderr);
285 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000286 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000291
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000292 /* Initialize _warnings. */
293 _PyWarnings_Init();
294
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000295 _PyTime_Init();
296
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200297 if (initfsencoding(interp) < 0)
298 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 if (install_sigs)
301 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 initmain(); /* Module __main__ */
304 if (initstdio() < 0)
305 Py_FatalError(
306 "Py_Initialize: can't initialize sys standard streams");
307
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000308 /* Initialize warnings. */
309 if (PySys_HasWarnOptions()) {
310 PyObject *warnings_module = PyImport_ImportModule("warnings");
311 if (warnings_module == NULL) {
312 fprintf(stderr, "'import warnings' failed; traceback:\n");
313 PyErr_Print();
314 }
315 Py_XDECREF(warnings_module);
316 }
317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 if (!Py_NoSiteFlag)
319 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000320}
321
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000322void
323Py_Initialize(void)
324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000326}
327
328
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000329#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000330extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000331#endif
332
Guido van Rossume8432ac2007-07-09 15:04:50 +0000333/* Flush stdout and stderr */
334
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100335static int
336file_is_closed(PyObject *fobj)
337{
338 int r;
339 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
340 if (tmp == NULL) {
341 PyErr_Clear();
342 return 0;
343 }
344 r = PyObject_IsTrue(tmp);
345 Py_DECREF(tmp);
346 if (r < 0)
347 PyErr_Clear();
348 return r > 0;
349}
350
Neal Norwitz2bad9702007-08-27 06:19:22 +0000351static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000352flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 PyObject *fout = PySys_GetObject("stdout");
355 PyObject *ferr = PySys_GetObject("stderr");
356 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000357
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100358 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 tmp = PyObject_CallMethod(fout, "flush", "");
360 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000361 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 else
363 Py_DECREF(tmp);
364 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000365
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100366 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 tmp = PyObject_CallMethod(ferr, "flush", "");
368 if (tmp == NULL)
369 PyErr_Clear();
370 else
371 Py_DECREF(tmp);
372 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000373}
374
Guido van Rossum25ce5661997-08-02 03:10:38 +0000375/* Undo the effect of Py_Initialize().
376
377 Beware: if multiple interpreter and/or thread states exist, these
378 are not wiped out; only the current thread and interpreter state
379 are deleted. But since everything else is deleted, those other
380 interpreter and thread states should no longer be used.
381
382 (XXX We should do better, e.g. wipe out all interpreters and
383 threads.)
384
385 Locking: as above.
386
387*/
388
389void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000390Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 PyInterpreterState *interp;
393 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (!initialized)
396 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 /* The interpreter is still entirely intact at this point, and the
401 * exit funcs may be relying on that. In particular, if some thread
402 * or exit func is still waiting to do an import, the import machinery
403 * expects Py_IsInitialized() to return true. So don't say the
404 * interpreter is uninitialized until after the exit funcs have run.
405 * Note that Threading.py uses an exit func to do a join on all the
406 * threads created thru it, so this also protects pending imports in
407 * the threads created via Threading.
408 */
409 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 /* Get current thread state and interpreter pointer */
412 tstate = PyThreadState_GET();
413 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000414
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200415 /* Remaining threads (e.g. daemon threads) will automatically exit
416 after taking the GIL (in PyEval_RestoreThread()). */
417 _Py_Finalizing = tstate;
418 initialized = 0;
419
420 /* Flush stdout+stderr */
421 flush_std_files();
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 /* Disable signal handling */
424 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 /* Clear type lookup cache */
427 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Collect garbage. This may call finalizers; it's nice to call these
430 * before all modules are destroyed.
431 * XXX If a __del__ or weakref callback is triggered here, and tries to
432 * XXX import a module, bad things can happen, because Python no
433 * XXX longer believes it's initialized.
434 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
435 * XXX is easy to provoke that way. I've also seen, e.g.,
436 * XXX Exception exceptions.ImportError: 'No module named sha'
437 * XXX in <function callback at 0x008F5718> ignored
438 * XXX but I'm unclear on exactly how that one happens. In any case,
439 * XXX I haven't seen a real-life report of either of these.
440 */
441 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000442#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* With COUNT_ALLOCS, it helps to run GC multiple times:
444 each collection might release some types from the type
445 list, so they become garbage. */
446 while (PyGC_Collect() > 0)
447 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000448#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000449 /* We run this while most interpreter state is still alive, so that
450 debug information can be printed out */
451 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* Destroy all modules */
454 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 /* Flush stdout+stderr (again, in case more was printed) */
457 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 /* Collect final garbage. This disposes of cycles created by
460 * new-style class definitions, for example.
461 * XXX This is disabled because it caused too many problems. If
462 * XXX a __del__ or weakref callback triggers here, Python code has
463 * XXX a hard time running, because even the sys module has been
464 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
465 * XXX One symptom is a sequence of information-free messages
466 * XXX coming from threads (if a __del__ or callback is invoked,
467 * XXX other threads can execute too, and any exception they encounter
468 * XXX triggers a comedy of errors as subsystem after subsystem
469 * XXX fails to find what it *expects* to find in sys to help report
470 * XXX the exception and consequent unexpected failures). I've also
471 * XXX seen segfaults then, after adding print statements to the
472 * XXX Python code getting called.
473 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000474#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000476#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
479 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000482#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000484#endif
485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000487
Tim Peters9cf25ce2003-04-17 15:21:01 +0000488#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* Display all objects still alive -- this can invoke arbitrary
490 * __repr__ overrides, so requires a mostly-intact interpreter.
491 * Alas, a lot of stuff may still be alive now that will be cleaned
492 * up later.
493 */
494 if (Py_GETENV("PYTHONDUMPREFS"))
495 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000496#endif /* Py_TRACE_REFS */
497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 /* Clear interpreter state */
499 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* Now we decref the exception classes. After this point nothing
502 can raise an exception. That's okay, because each Fini() method
503 below has been checked to make sure no exceptions are ever
504 raised.
505 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000510#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000512#endif /* WITH_THREAD */
513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 /* Delete current thread */
515 PyThreadState_Swap(NULL);
516 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* Sundry finalizers */
519 PyMethod_Fini();
520 PyFrame_Fini();
521 PyCFunction_Fini();
522 PyTuple_Fini();
523 PyList_Fini();
524 PySet_Fini();
525 PyBytes_Fini();
526 PyByteArray_Fini();
527 PyLong_Fini();
528 PyFloat_Fini();
529 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 /* Cleanup Unicode implementation */
532 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000535 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 free((char*)Py_FileSystemDefaultEncoding);
537 Py_FileSystemDefaultEncoding = NULL;
538 }
Christian Heimesc8967002007-11-30 10:18:26 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 /* XXX Still allocated:
541 - various static ad-hoc pointers to interned strings
542 - int and float free list blocks
543 - whatever various modules and libraries allocate
544 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000547
Tim Peters269b2a62003-04-17 19:52:29 +0000548#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 /* Display addresses (& refcnts) of all objects still alive.
550 * An address can be used to find the repr of the object, printed
551 * above by _Py_PrintReferences.
552 */
553 if (Py_GETENV("PYTHONDUMPREFS"))
554 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000555#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000556#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (Py_GETENV("PYTHONMALLOCSTATS"))
558 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000559#endif
560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562}
563
564/* Create and initialize a new interpreter and thread, and return the
565 new thread. This requires that Py_Initialize() has been called
566 first.
567
568 Unsuccessful initialization yields a NULL pointer. Note that *no*
569 exception information is available even in this case -- the
570 exception information is held in the thread, and there is no
571 thread.
572
573 Locking: as above.
574
575*/
576
577PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000578Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 PyInterpreterState *interp;
581 PyThreadState *tstate, *save_tstate;
582 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (!initialized)
585 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 interp = PyInterpreterState_New();
588 if (interp == NULL)
589 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 tstate = PyThreadState_New(interp);
592 if (tstate == NULL) {
593 PyInterpreterState_Delete(interp);
594 return NULL;
595 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 interp->modules = PyDict_New();
602 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000603
Victor Stinner49d3f252010-10-17 01:24:53 +0000604 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (bimod != NULL) {
606 interp->builtins = PyModule_GetDict(bimod);
607 if (interp->builtins == NULL)
608 goto handle_error;
609 Py_INCREF(interp->builtins);
610 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* initialize builtin exceptions */
613 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000614
Victor Stinner49d3f252010-10-17 01:24:53 +0000615 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (bimod != NULL && sysmod != NULL) {
617 PyObject *pstderr;
618 interp->sysdict = PyModule_GetDict(sysmod);
619 if (interp->sysdict == NULL)
620 goto handle_error;
621 Py_INCREF(interp->sysdict);
622 PySys_SetPath(Py_GetPath());
623 PyDict_SetItemString(interp->sysdict, "modules",
624 interp->modules);
625 /* Set up a preliminary stderr printer until we have enough
626 infrastructure for the io module in place. */
627 pstderr = PyFile_NewStdPrinter(fileno(stderr));
628 if (pstderr == NULL)
629 Py_FatalError("Py_Initialize: can't set preliminary stderr");
630 PySys_SetObject("stderr", pstderr);
631 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000632 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 _PyImportHooks_Init();
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200635
636 if (initfsencoding(interp) < 0)
637 goto handle_error;
638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 if (initstdio() < 0)
640 Py_FatalError(
641 "Py_Initialize: can't initialize sys standard streams");
642 initmain();
643 if (!Py_NoSiteFlag)
644 initsite();
645 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (!PyErr_Occurred())
648 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Thomas Wouters89f507f2006-12-13 04:49:30 +0000650handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000652
Victor Stinner11889352011-04-27 00:20:27 +0200653 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyThreadState_Clear(tstate);
655 PyThreadState_Swap(save_tstate);
656 PyThreadState_Delete(tstate);
657 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000660}
661
662/* Delete an interpreter and its last thread. This requires that the
663 given thread state is current, that the thread has no remaining
664 frames, and that it is its interpreter's only remaining thread.
665 It is a fatal error to violate these constraints.
666
667 (Py_Finalize() doesn't have these constraints -- it zaps
668 everything, regardless.)
669
670 Locking: as above.
671
672*/
673
674void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000675Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 if (tstate != PyThreadState_GET())
680 Py_FatalError("Py_EndInterpreter: thread is not current");
681 if (tstate->frame != NULL)
682 Py_FatalError("Py_EndInterpreter: thread still has a frame");
683 if (tstate != interp->tstate_head || tstate->next != NULL)
684 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyImport_Cleanup();
687 PyInterpreterState_Clear(interp);
688 PyThreadState_Swap(NULL);
689 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000690}
691
Martin v. Löwis790465f2008-04-05 20:41:37 +0000692static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000693
694void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000695Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 if (pn && *pn)
698 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000699}
700
Martin v. Löwis790465f2008-04-05 20:41:37 +0000701wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000702Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000705}
706
Martin v. Löwis790465f2008-04-05 20:41:37 +0000707static wchar_t *default_home = NULL;
708static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000709
710void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000711Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000714}
715
Martin v. Löwis790465f2008-04-05 20:41:37 +0000716wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000717Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 wchar_t *home = default_home;
720 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
721 char* chome = Py_GETENV("PYTHONHOME");
722 if (chome) {
723 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
724 if (r != (size_t)-1 && r <= PATH_MAX)
725 home = env_home;
726 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 }
729 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000730}
731
Guido van Rossum6135a871995-01-09 17:53:26 +0000732/* Create __main__ module */
733
734static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000735initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyObject *m, *d;
738 m = PyImport_AddModule("__main__");
739 if (m == NULL)
740 Py_FatalError("can't create __main__ module");
741 d = PyModule_GetDict(m);
742 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
743 PyObject *bimod = PyImport_ImportModule("builtins");
744 if (bimod == NULL ||
745 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
746 Py_FatalError("can't add __builtins__ to __main__");
747 Py_DECREF(bimod);
748 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000749}
750
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200751static int
752initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000753{
754 PyObject *codec;
755#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000756 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000757
Victor Stinner7f84ab52010-06-11 00:36:33 +0000758 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000759 /* On Unix, set the file system encoding according to the
760 user's preference, if the CODESET names a well-known
761 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000762 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000763 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000764 if (codeset == NULL)
765 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000766
Victor Stinnere4743092010-10-19 00:05:51 +0000767 Py_FileSystemDefaultEncoding = codeset;
768 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200769 interp->fscodec_initialized = 1;
770 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000771 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000772#endif
773
774 /* the encoding is mbcs, utf-8 or ascii */
775 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
776 if (!codec) {
777 /* Such error can only occurs in critical situations: no more
778 * memory, import a module of the standard library failed,
779 * etc. */
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200780 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000781 }
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200782 Py_DECREF(codec);
783 interp->fscodec_initialized = 1;
784 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000785}
786
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000787/* Import the site module (not into __main__ though) */
788
789static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000790initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 PyObject *m;
793 m = PyImport_ImportModule("site");
794 if (m == NULL) {
795 PyErr_Print();
796 Py_Finalize();
797 exit(1);
798 }
799 else {
800 Py_DECREF(m);
801 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000802}
803
Antoine Pitrou05608432009-01-09 18:53:14 +0000804static PyObject*
805create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 int fd, int write_mode, char* name,
807 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
810 const char* mode;
Victor Stinner02bfdb32011-02-23 12:10:23 +0000811 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyObject *line_buffering;
813 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 /* stdin is always opened in buffered mode, first because it shouldn't
816 make a difference in common use cases, second because TextIOWrapper
817 depends on the presence of a read1() method which only exists on
818 buffered streams.
819 */
820 if (Py_UnbufferedStdioFlag && write_mode)
821 buffering = 0;
822 else
823 buffering = -1;
824 if (write_mode)
825 mode = "wb";
826 else
827 mode = "rb";
828 buf = PyObject_CallMethod(io, "open", "isiOOOi",
829 fd, mode, buffering,
830 Py_None, Py_None, Py_None, 0);
831 if (buf == NULL)
832 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 if (buffering) {
835 raw = PyObject_GetAttrString(buf, "raw");
836 if (raw == NULL)
837 goto error;
838 }
839 else {
840 raw = buf;
841 Py_INCREF(raw);
842 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 text = PyUnicode_FromString(name);
845 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
846 goto error;
847 res = PyObject_CallMethod(raw, "isatty", "");
848 if (res == NULL)
849 goto error;
850 isatty = PyObject_IsTrue(res);
851 Py_DECREF(res);
852 if (isatty == -1)
853 goto error;
854 if (isatty || Py_UnbufferedStdioFlag)
855 line_buffering = Py_True;
856 else
857 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 Py_CLEAR(raw);
860 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000861
Victor Stinner02bfdb32011-02-23 12:10:23 +0000862 newline = "\n";
863#ifdef MS_WINDOWS
864 if (!write_mode) {
865 /* translate \r\n to \n for sys.stdin on Windows */
866 newline = NULL;
867 }
868#endif
869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
871 buf, encoding, errors,
Victor Stinner02bfdb32011-02-23 12:10:23 +0000872 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 Py_CLEAR(buf);
874 if (stream == NULL)
875 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 if (write_mode)
878 mode = "w";
879 else
880 mode = "r";
881 text = PyUnicode_FromString(mode);
882 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
883 goto error;
884 Py_CLEAR(text);
885 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000886
887error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 Py_XDECREF(buf);
889 Py_XDECREF(stream);
890 Py_XDECREF(text);
891 Py_XDECREF(raw);
892 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000893}
894
Antoine Pitrou11942a52011-11-28 19:08:36 +0100895static int
896is_valid_fd(int fd)
897{
898 int dummy_fd;
899 if (fd < 0 || !_PyVerify_fd(fd))
900 return 0;
901 dummy_fd = dup(fd);
902 if (dummy_fd < 0)
903 return 0;
904 close(dummy_fd);
905 return 1;
906}
907
Georg Brandl1a3284e2007-12-02 09:40:06 +0000908/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000909static int
910initstdio(void)
911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 PyObject *iomod = NULL, *wrapper;
913 PyObject *bimod = NULL;
914 PyObject *m;
915 PyObject *std = NULL;
916 int status = 0, fd;
917 PyObject * encoding_attr;
918 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Hack to avoid a nasty recursion issue when Python is invoked
921 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
922 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
923 goto error;
924 }
925 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
928 goto error;
929 }
930 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 if (!(bimod = PyImport_ImportModule("builtins"))) {
933 goto error;
934 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if (!(iomod = PyImport_ImportModule("io"))) {
937 goto error;
938 }
939 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
940 goto error;
941 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 /* Set builtins.open */
944 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000945 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 goto error;
947 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000948 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 encoding = Py_GETENV("PYTHONIOENCODING");
951 errors = NULL;
952 if (encoding) {
953 encoding = strdup(encoding);
954 errors = strchr(encoding, ':');
955 if (errors) {
956 *errors = '\0';
957 errors++;
958 }
959 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* Set sys.stdin */
962 fd = fileno(stdin);
963 /* Under some conditions stdin, stdout and stderr may not be connected
964 * and fileno() may point to an invalid file descriptor. For example
965 * GUI apps don't have valid standard streams by default.
966 */
Antoine Pitrou11942a52011-11-28 19:08:36 +0100967 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 std = Py_None;
969 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 }
971 else {
972 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
973 if (std == NULL)
974 goto error;
975 } /* if (fd < 0) */
976 PySys_SetObject("__stdin__", std);
977 PySys_SetObject("stdin", std);
978 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 /* Set sys.stdout */
981 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +0100982 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 std = Py_None;
984 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 }
986 else {
987 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
988 if (std == NULL)
989 goto error;
990 } /* if (fd < 0) */
991 PySys_SetObject("__stdout__", std);
992 PySys_SetObject("stdout", std);
993 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000994
Guido van Rossum98297ee2007-11-06 21:34:58 +0000995#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 /* Set sys.stderr, replaces the preliminary stderr */
997 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +0100998 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 std = Py_None;
1000 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 }
1002 else {
1003 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1004 if (std == NULL)
1005 goto error;
1006 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* Same as hack above, pre-import stderr's codec to avoid recursion
1009 when import.c tries to write to stderr in verbose mode. */
1010 encoding_attr = PyObject_GetAttrString(std, "encoding");
1011 if (encoding_attr != NULL) {
1012 const char * encoding;
1013 encoding = _PyUnicode_AsString(encoding_attr);
1014 if (encoding != NULL) {
1015 _PyCodec_Lookup(encoding);
1016 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001017 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 }
1019 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 PySys_SetObject("__stderr__", std);
1022 PySys_SetObject("stderr", std);
1023 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001024#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001027 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 status = -1;
1029 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (encoding)
1032 free(encoding);
1033 Py_XDECREF(bimod);
1034 Py_XDECREF(iomod);
1035 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001036}
1037
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001038/* Parse input from a file and execute it */
1039
1040int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001041PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 if (filename == NULL)
1045 filename = "???";
1046 if (Py_FdIsInteractive(fp, filename)) {
1047 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1048 if (closeit)
1049 fclose(fp);
1050 return err;
1051 }
1052 else
1053 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001054}
1055
1056int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001057PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 PyObject *v;
1060 int ret;
1061 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 if (flags == NULL) {
1064 flags = &local_flags;
1065 local_flags.cf_flags = 0;
1066 }
1067 v = PySys_GetObject("ps1");
1068 if (v == NULL) {
1069 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1070 Py_XDECREF(v);
1071 }
1072 v = PySys_GetObject("ps2");
1073 if (v == NULL) {
1074 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1075 Py_XDECREF(v);
1076 }
1077 for (;;) {
1078 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1079 PRINT_TOTAL_REFS();
1080 if (ret == E_EOF)
1081 return 0;
1082 /*
1083 if (ret == E_NOMEM)
1084 return -1;
1085 */
1086 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001087}
1088
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001089/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001090static int PARSER_FLAGS(PyCompilerFlags *flags)
1091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 int parser_flags = 0;
1093 if (!flags)
1094 return 0;
1095 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1096 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1097 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1098 parser_flags |= PyPARSE_IGNORE_COOKIE;
1099 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1100 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1101 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001102}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001103
Thomas Wouters89f507f2006-12-13 04:49:30 +00001104#if 0
1105/* Keep an example of flags with future keyword support. */
1106#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1108 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1109 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1110 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001111#endif
1112
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001113int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001114PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 PyObject *m, *d, *v, *w, *oenc = NULL;
1117 mod_ty mod;
1118 PyArena *arena;
1119 char *ps1 = "", *ps2 = "", *enc = NULL;
1120 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 if (fp == stdin) {
1123 /* Fetch encoding from sys.stdin */
1124 v = PySys_GetObject("stdin");
1125 if (v == NULL || v == Py_None)
1126 return -1;
1127 oenc = PyObject_GetAttrString(v, "encoding");
1128 if (!oenc)
1129 return -1;
1130 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001131 if (enc == NULL)
1132 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 }
1134 v = PySys_GetObject("ps1");
1135 if (v != NULL) {
1136 v = PyObject_Str(v);
1137 if (v == NULL)
1138 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001139 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001141 if (ps1 == NULL) {
1142 PyErr_Clear();
1143 ps1 = "";
1144 }
1145 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 }
1147 w = PySys_GetObject("ps2");
1148 if (w != NULL) {
1149 w = PyObject_Str(w);
1150 if (w == NULL)
1151 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001152 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001154 if (ps2 == NULL) {
1155 PyErr_Clear();
1156 ps2 = "";
1157 }
1158 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 }
1160 arena = PyArena_New();
1161 if (arena == NULL) {
1162 Py_XDECREF(v);
1163 Py_XDECREF(w);
1164 Py_XDECREF(oenc);
1165 return -1;
1166 }
1167 mod = PyParser_ASTFromFile(fp, filename, enc,
1168 Py_single_input, ps1, ps2,
1169 flags, &errcode, arena);
1170 Py_XDECREF(v);
1171 Py_XDECREF(w);
1172 Py_XDECREF(oenc);
1173 if (mod == NULL) {
1174 PyArena_Free(arena);
1175 if (errcode == E_EOF) {
1176 PyErr_Clear();
1177 return E_EOF;
1178 }
1179 PyErr_Print();
1180 return -1;
1181 }
1182 m = PyImport_AddModule("__main__");
1183 if (m == NULL) {
1184 PyArena_Free(arena);
1185 return -1;
1186 }
1187 d = PyModule_GetDict(m);
1188 v = run_mod(mod, filename, d, d, flags, arena);
1189 PyArena_Free(arena);
1190 flush_io();
1191 if (v == NULL) {
1192 PyErr_Print();
1193 return -1;
1194 }
1195 Py_DECREF(v);
1196 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001197}
1198
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001199/* Check whether a file maybe a pyc file: Look at the extension,
1200 the file type, and, if we may close it, at the first few bytes. */
1201
1202static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001203maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1206 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 /* Only look into the file if we are allowed to close it, since
1209 it then should also be seekable. */
1210 if (closeit) {
1211 /* Read only two bytes of the magic. If the file was opened in
1212 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1213 be read as they are on disk. */
1214 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1215 unsigned char buf[2];
1216 /* Mess: In case of -x, the stream is NOT at its start now,
1217 and ungetc() was used to push back the first newline,
1218 which makes the current stream position formally undefined,
1219 and a x-platform nightmare.
1220 Unfortunately, we have no direct way to know whether -x
1221 was specified. So we use a terrible hack: if the current
1222 stream position is not 0, we assume -x was specified, and
1223 give up. Bug 132850 on SourceForge spells out the
1224 hopelessness of trying anything else (fseek and ftell
1225 don't work predictably x-platform for text-mode files).
1226 */
1227 int ispyc = 0;
1228 if (ftell(fp) == 0) {
1229 if (fread(buf, 1, 2, fp) == 2 &&
1230 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1231 ispyc = 1;
1232 rewind(fp);
1233 }
1234 return ispyc;
1235 }
1236 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001237}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001238
Guido van Rossum0df002c2000-08-27 19:21:52 +00001239int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001240PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 PyObject *m, *d, *v;
1244 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001245 int set_file_name = 0, ret;
1246 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 m = PyImport_AddModule("__main__");
1249 if (m == NULL)
1250 return -1;
1251 d = PyModule_GetDict(m);
1252 if (PyDict_GetItemString(d, "__file__") == NULL) {
1253 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001254 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (f == NULL)
1256 return -1;
1257 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1258 Py_DECREF(f);
1259 return -1;
1260 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001261 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1262 Py_DECREF(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 return -1;
Barry Warsaw916048d2011-09-20 14:45:44 -04001264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 set_file_name = 1;
1266 Py_DECREF(f);
1267 }
1268 len = strlen(filename);
1269 ext = filename + len - (len > 4 ? 4 : 0);
1270 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1271 /* Try to run a pyc file. First, re-open in binary */
1272 if (closeit)
1273 fclose(fp);
1274 if ((fp = fopen(filename, "rb")) == NULL) {
1275 fprintf(stderr, "python: Can't reopen .pyc file\n");
1276 ret = -1;
1277 goto done;
1278 }
1279 /* Turn on optimization if a .pyo file is given */
1280 if (strcmp(ext, ".pyo") == 0)
1281 Py_OptimizeFlag = 1;
1282 v = run_pyc_file(fp, filename, d, d, flags);
1283 } else {
1284 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1285 closeit, flags);
1286 }
1287 flush_io();
1288 if (v == NULL) {
1289 PyErr_Print();
1290 ret = -1;
1291 goto done;
1292 }
1293 Py_DECREF(v);
1294 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001295 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1297 PyErr_Clear();
1298 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001299}
1300
1301int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001302PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyObject *m, *d, *v;
1305 m = PyImport_AddModule("__main__");
1306 if (m == NULL)
1307 return -1;
1308 d = PyModule_GetDict(m);
1309 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1310 if (v == NULL) {
1311 PyErr_Print();
1312 return -1;
1313 }
1314 Py_DECREF(v);
1315 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001316}
1317
Barry Warsaw035574d1997-08-29 22:07:17 +00001318static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001319parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 long hold;
1323 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* old style errors */
1326 if (PyTuple_Check(err))
1327 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1328 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 if (! (v = PyObject_GetAttrString(err, "msg")))
1333 goto finally;
1334 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (!(v = PyObject_GetAttrString(err, "filename")))
1337 goto finally;
1338 if (v == Py_None)
1339 *filename = NULL;
1340 else if (! (*filename = _PyUnicode_AsString(v)))
1341 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 Py_DECREF(v);
1344 if (!(v = PyObject_GetAttrString(err, "lineno")))
1345 goto finally;
1346 hold = PyLong_AsLong(v);
1347 Py_DECREF(v);
1348 v = NULL;
1349 if (hold < 0 && PyErr_Occurred())
1350 goto finally;
1351 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 if (!(v = PyObject_GetAttrString(err, "offset")))
1354 goto finally;
1355 if (v == Py_None) {
1356 *offset = -1;
1357 Py_DECREF(v);
1358 v = NULL;
1359 } else {
1360 hold = PyLong_AsLong(v);
1361 Py_DECREF(v);
1362 v = NULL;
1363 if (hold < 0 && PyErr_Occurred())
1364 goto finally;
1365 *offset = (int)hold;
1366 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (!(v = PyObject_GetAttrString(err, "text")))
1369 goto finally;
1370 if (v == Py_None)
1371 *text = NULL;
1372 else if (!PyUnicode_Check(v) ||
1373 !(*text = _PyUnicode_AsString(v)))
1374 goto finally;
1375 Py_DECREF(v);
1376 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001377
1378finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 Py_XDECREF(v);
1380 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001381}
1382
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001383void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001384PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001387}
1388
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001389static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001390print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 char *nl;
1393 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001394 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1395 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 for (;;) {
1397 nl = strchr(text, '\n');
1398 if (nl == NULL || nl-text >= offset)
1399 break;
1400 offset -= (int)(nl+1-text);
1401 text = nl+1;
1402 }
1403 while (*text == ' ' || *text == '\t') {
1404 text++;
1405 offset--;
1406 }
1407 }
1408 PyFile_WriteString(" ", f);
1409 PyFile_WriteString(text, f);
1410 if (*text == '\0' || text[strlen(text)-1] != '\n')
1411 PyFile_WriteString("\n", f);
1412 if (offset == -1)
1413 return;
1414 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001415 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001418}
1419
Guido van Rossum66e8e862001-03-23 17:54:43 +00001420static void
1421handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 PyObject *exception, *value, *tb;
1424 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (Py_InspectFlag)
1427 /* Don't exit if -i flag was given. This flag is set to 0
1428 * when entering interactive mode for inspecting. */
1429 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyErr_Fetch(&exception, &value, &tb);
1432 fflush(stdout);
1433 if (value == NULL || value == Py_None)
1434 goto done;
1435 if (PyExceptionInstance_Check(value)) {
1436 /* The error code should be in the `code' attribute. */
1437 PyObject *code = PyObject_GetAttrString(value, "code");
1438 if (code) {
1439 Py_DECREF(value);
1440 value = code;
1441 if (value == Py_None)
1442 goto done;
1443 }
1444 /* If we failed to dig out the 'code' attribute,
1445 just let the else clause below print the error. */
1446 }
1447 if (PyLong_Check(value))
1448 exitcode = (int)PyLong_AsLong(value);
1449 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001450 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001451 if (sys_stderr != NULL && sys_stderr != Py_None) {
1452 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1453 } else {
1454 PyObject_Print(value, stderr, Py_PRINT_RAW);
1455 fflush(stderr);
1456 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 PySys_WriteStderr("\n");
1458 exitcode = 1;
1459 }
Tim Peterscf615b52003-04-19 18:47:02 +00001460 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 /* Restore and clear the exception info, in order to properly decref
1462 * the exception, value, and traceback. If we just exit instead,
1463 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1464 * some finalizers from running.
1465 */
1466 PyErr_Restore(exception, value, tb);
1467 PyErr_Clear();
1468 Py_Exit(exitcode);
1469 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001470}
1471
1472void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001473PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1478 handle_system_exit();
1479 }
1480 PyErr_Fetch(&exception, &v, &tb);
1481 if (exception == NULL)
1482 return;
1483 PyErr_NormalizeException(&exception, &v, &tb);
1484 if (tb == NULL) {
1485 tb = Py_None;
1486 Py_INCREF(tb);
1487 }
1488 PyException_SetTraceback(v, tb);
1489 if (exception == NULL)
1490 return;
1491 /* Now we know v != NULL too */
1492 if (set_sys_last_vars) {
1493 PySys_SetObject("last_type", exception);
1494 PySys_SetObject("last_value", v);
1495 PySys_SetObject("last_traceback", tb);
1496 }
1497 hook = PySys_GetObject("excepthook");
1498 if (hook) {
1499 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1500 PyObject *result = PyEval_CallObject(hook, args);
1501 if (result == NULL) {
1502 PyObject *exception2, *v2, *tb2;
1503 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1504 handle_system_exit();
1505 }
1506 PyErr_Fetch(&exception2, &v2, &tb2);
1507 PyErr_NormalizeException(&exception2, &v2, &tb2);
1508 /* It should not be possible for exception2 or v2
1509 to be NULL. However PyErr_Display() can't
1510 tolerate NULLs, so just be safe. */
1511 if (exception2 == NULL) {
1512 exception2 = Py_None;
1513 Py_INCREF(exception2);
1514 }
1515 if (v2 == NULL) {
1516 v2 = Py_None;
1517 Py_INCREF(v2);
1518 }
1519 fflush(stdout);
1520 PySys_WriteStderr("Error in sys.excepthook:\n");
1521 PyErr_Display(exception2, v2, tb2);
1522 PySys_WriteStderr("\nOriginal exception was:\n");
1523 PyErr_Display(exception, v, tb);
1524 Py_DECREF(exception2);
1525 Py_DECREF(v2);
1526 Py_XDECREF(tb2);
1527 }
1528 Py_XDECREF(result);
1529 Py_XDECREF(args);
1530 } else {
1531 PySys_WriteStderr("sys.excepthook is missing\n");
1532 PyErr_Display(exception, v, tb);
1533 }
1534 Py_XDECREF(exception);
1535 Py_XDECREF(v);
1536 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001537}
1538
Benjamin Petersone6528212008-07-15 15:32:09 +00001539static void
1540print_exception(PyObject *f, PyObject *value)
1541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 int err = 0;
1543 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (!PyExceptionInstance_Check(value)) {
1546 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1547 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1548 PyFile_WriteString(" found\n", f);
1549 return;
1550 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 Py_INCREF(value);
1553 fflush(stdout);
1554 type = (PyObject *) Py_TYPE(value);
1555 tb = PyException_GetTraceback(value);
1556 if (tb && tb != Py_None)
1557 err = PyTraceBack_Print(tb, f);
1558 if (err == 0 &&
1559 PyObject_HasAttrString(value, "print_file_and_line"))
1560 {
1561 PyObject *message;
1562 const char *filename, *text;
1563 int lineno, offset;
1564 if (!parse_syntax_error(value, &message, &filename,
1565 &lineno, &offset, &text))
1566 PyErr_Clear();
1567 else {
1568 char buf[10];
1569 PyFile_WriteString(" File \"", f);
1570 if (filename == NULL)
1571 PyFile_WriteString("<string>", f);
1572 else
1573 PyFile_WriteString(filename, f);
1574 PyFile_WriteString("\", line ", f);
1575 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1576 PyFile_WriteString(buf, f);
1577 PyFile_WriteString("\n", f);
1578 if (text != NULL)
1579 print_error_text(f, offset, text);
1580 Py_DECREF(value);
1581 value = message;
1582 /* Can't be bothered to check all those
1583 PyFile_WriteString() calls */
1584 if (PyErr_Occurred())
1585 err = -1;
1586 }
1587 }
1588 if (err) {
1589 /* Don't do anything else */
1590 }
1591 else {
1592 PyObject* moduleName;
1593 char* className;
1594 assert(PyExceptionClass_Check(type));
1595 className = PyExceptionClass_Name(type);
1596 if (className != NULL) {
1597 char *dot = strrchr(className, '.');
1598 if (dot != NULL)
1599 className = dot+1;
1600 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 moduleName = PyObject_GetAttrString(type, "__module__");
1603 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1604 {
1605 Py_DECREF(moduleName);
1606 err = PyFile_WriteString("<unknown>", f);
1607 }
1608 else {
1609 char* modstr = _PyUnicode_AsString(moduleName);
1610 if (modstr && strcmp(modstr, "builtins"))
1611 {
1612 err = PyFile_WriteString(modstr, f);
1613 err += PyFile_WriteString(".", f);
1614 }
1615 Py_DECREF(moduleName);
1616 }
1617 if (err == 0) {
1618 if (className == NULL)
1619 err = PyFile_WriteString("<unknown>", f);
1620 else
1621 err = PyFile_WriteString(className, f);
1622 }
1623 }
1624 if (err == 0 && (value != Py_None)) {
1625 PyObject *s = PyObject_Str(value);
1626 /* only print colon if the str() of the
1627 object is not the empty string
1628 */
1629 if (s == NULL)
1630 err = -1;
1631 else if (!PyUnicode_Check(s) ||
1632 PyUnicode_GetSize(s) != 0)
1633 err = PyFile_WriteString(": ", f);
1634 if (err == 0)
1635 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1636 Py_XDECREF(s);
1637 }
1638 /* try to write a newline in any case */
1639 err += PyFile_WriteString("\n", f);
1640 Py_XDECREF(tb);
1641 Py_DECREF(value);
1642 /* If an error happened here, don't show it.
1643 XXX This is wrong, but too many callers rely on this behavior. */
1644 if (err != 0)
1645 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001646}
1647
1648static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 "\nThe above exception was the direct cause "
1650 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001651
1652static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 "\nDuring handling of the above exception, "
1654 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001655
1656static void
1657print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 int err = 0, res;
1660 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 if (seen != NULL) {
1663 /* Exception chaining */
1664 if (PySet_Add(seen, value) == -1)
1665 PyErr_Clear();
1666 else if (PyExceptionInstance_Check(value)) {
1667 cause = PyException_GetCause(value);
1668 context = PyException_GetContext(value);
1669 if (cause) {
1670 res = PySet_Contains(seen, cause);
1671 if (res == -1)
1672 PyErr_Clear();
1673 if (res == 0) {
1674 print_exception_recursive(
1675 f, cause, seen);
1676 err |= PyFile_WriteString(
1677 cause_message, f);
1678 }
1679 }
1680 else if (context) {
1681 res = PySet_Contains(seen, context);
1682 if (res == -1)
1683 PyErr_Clear();
1684 if (res == 0) {
1685 print_exception_recursive(
1686 f, context, seen);
1687 err |= PyFile_WriteString(
1688 context_message, f);
1689 }
1690 }
1691 Py_XDECREF(context);
1692 Py_XDECREF(cause);
1693 }
1694 }
1695 print_exception(f, value);
1696 if (err != 0)
1697 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001698}
1699
Thomas Wouters477c8d52006-05-27 19:21:47 +00001700void
1701PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 PyObject *seen;
1704 PyObject *f = PySys_GetObject("stderr");
1705 if (f == Py_None) {
1706 /* pass */
1707 }
1708 else if (f == NULL) {
1709 _PyObject_Dump(value);
1710 fprintf(stderr, "lost sys.stderr\n");
1711 }
1712 else {
1713 /* We choose to ignore seen being possibly NULL, and report
1714 at least the main exception (it could be a MemoryError).
1715 */
1716 seen = PySet_New(NULL);
1717 if (seen == NULL)
1718 PyErr_Clear();
1719 print_exception_recursive(f, value, seen);
1720 Py_XDECREF(seen);
1721 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001722}
1723
Guido van Rossum82598051997-03-05 00:20:32 +00001724PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001725PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 PyObject *ret = NULL;
1729 mod_ty mod;
1730 PyArena *arena = PyArena_New();
1731 if (arena == NULL)
1732 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1735 if (mod != NULL)
1736 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1737 PyArena_Free(arena);
1738 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001739}
1740
1741PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001742PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 PyObject *ret;
1746 mod_ty mod;
1747 PyArena *arena = PyArena_New();
1748 if (arena == NULL)
1749 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1752 flags, NULL, arena);
1753 if (closeit)
1754 fclose(fp);
1755 if (mod == NULL) {
1756 PyArena_Free(arena);
1757 return NULL;
1758 }
1759 ret = run_mod(mod, filename, globals, locals, flags, arena);
1760 PyArena_Free(arena);
1761 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001762}
1763
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001764static void
1765flush_io(void)
1766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 PyObject *f, *r;
1768 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 /* Save the current exception */
1771 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 f = PySys_GetObject("stderr");
1774 if (f != NULL) {
1775 r = PyObject_CallMethod(f, "flush", "");
1776 if (r)
1777 Py_DECREF(r);
1778 else
1779 PyErr_Clear();
1780 }
1781 f = PySys_GetObject("stdout");
1782 if (f != NULL) {
1783 r = PyObject_CallMethod(f, "flush", "");
1784 if (r)
1785 Py_DECREF(r);
1786 else
1787 PyErr_Clear();
1788 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001791}
1792
Guido van Rossum82598051997-03-05 00:20:32 +00001793static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyCodeObject *co;
1798 PyObject *v;
1799 co = PyAST_Compile(mod, filename, flags, arena);
1800 if (co == NULL)
1801 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001802 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 Py_DECREF(co);
1804 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001805}
1806
Guido van Rossum82598051997-03-05 00:20:32 +00001807static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001808run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 PyCodeObject *co;
1812 PyObject *v;
1813 long magic;
1814 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 magic = PyMarshal_ReadLongFromFile(fp);
1817 if (magic != PyImport_GetMagicNumber()) {
1818 PyErr_SetString(PyExc_RuntimeError,
1819 "Bad magic number in .pyc file");
1820 return NULL;
1821 }
1822 (void) PyMarshal_ReadLongFromFile(fp);
1823 v = PyMarshal_ReadLastObjectFromFile(fp);
1824 fclose(fp);
1825 if (v == NULL || !PyCode_Check(v)) {
1826 Py_XDECREF(v);
1827 PyErr_SetString(PyExc_RuntimeError,
1828 "Bad code object in .pyc file");
1829 return NULL;
1830 }
1831 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001832 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 if (v && flags)
1834 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1835 Py_DECREF(co);
1836 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001837}
1838
Guido van Rossum82598051997-03-05 00:20:32 +00001839PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001840Py_CompileStringExFlags(const char *str, const char *filename, int start,
1841 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyCodeObject *co;
1844 mod_ty mod;
1845 PyArena *arena = PyArena_New();
1846 if (arena == NULL)
1847 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1850 if (mod == NULL) {
1851 PyArena_Free(arena);
1852 return NULL;
1853 }
1854 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1855 PyObject *result = PyAST_mod2obj(mod);
1856 PyArena_Free(arena);
1857 return result;
1858 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001859 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 PyArena_Free(arena);
1861 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001862}
1863
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001864/* For use in Py_LIMITED_API */
1865#undef Py_CompileString
1866PyObject *
1867PyCompileString(const char *str, const char *filename, int start)
1868{
1869 return Py_CompileStringFlags(str, filename, start, NULL);
1870}
1871
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001872struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001873Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 struct symtable *st;
1876 mod_ty mod;
1877 PyCompilerFlags flags;
1878 PyArena *arena = PyArena_New();
1879 if (arena == NULL)
1880 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 flags.cf_flags = 0;
1883 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1884 if (mod == NULL) {
1885 PyArena_Free(arena);
1886 return NULL;
1887 }
1888 st = PySymtable_Build(mod, filename, 0);
1889 PyArena_Free(arena);
1890 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001891}
1892
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001893/* Preferred access to parser is through AST. */
1894mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001895PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 mod_ty mod;
1899 PyCompilerFlags localflags;
1900 perrdetail err;
1901 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1904 &_PyParser_Grammar, start, &err,
1905 &iflags);
1906 if (flags == NULL) {
1907 localflags.cf_flags = 0;
1908 flags = &localflags;
1909 }
1910 if (n) {
1911 flags->cf_flags |= iflags & PyCF_MASK;
1912 mod = PyAST_FromNode(n, flags, filename, arena);
1913 PyNode_Free(n);
1914 return mod;
1915 }
1916 else {
1917 err_input(&err);
1918 return NULL;
1919 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001920}
1921
1922mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001923PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 int start, char *ps1,
1925 char *ps2, PyCompilerFlags *flags, int *errcode,
1926 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 mod_ty mod;
1929 PyCompilerFlags localflags;
1930 perrdetail err;
1931 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1934 &_PyParser_Grammar,
1935 start, ps1, ps2, &err, &iflags);
1936 if (flags == NULL) {
1937 localflags.cf_flags = 0;
1938 flags = &localflags;
1939 }
1940 if (n) {
1941 flags->cf_flags |= iflags & PyCF_MASK;
1942 mod = PyAST_FromNode(n, flags, filename, arena);
1943 PyNode_Free(n);
1944 return mod;
1945 }
1946 else {
1947 err_input(&err);
1948 if (errcode)
1949 *errcode = err.error;
1950 return NULL;
1951 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001952}
1953
Guido van Rossuma110aa61994-08-29 12:50:44 +00001954/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001955
Guido van Rossuma110aa61994-08-29 12:50:44 +00001956node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001957PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 perrdetail err;
1960 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1961 &_PyParser_Grammar,
1962 start, NULL, NULL, &err, flags);
1963 if (n == NULL)
1964 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001967}
1968
Guido van Rossuma110aa61994-08-29 12:50:44 +00001969/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001970
Guido van Rossuma110aa61994-08-29 12:50:44 +00001971node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001972PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 perrdetail err;
1975 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1976 start, &err, flags);
1977 if (n == NULL)
1978 err_input(&err);
1979 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001980}
1981
1982node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001983PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 perrdetail err;
1987 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1988 &_PyParser_Grammar, start, &err, flags);
1989 if (n == NULL)
1990 err_input(&err);
1991 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001992}
1993
1994node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001995PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001998}
1999
Guido van Rossum66ebd912003-04-17 16:02:26 +00002000/* May want to move a more generalized form of this to parsetok.c or
2001 even parser modules. */
2002
2003void
2004PyParser_SetError(perrdetail *err)
2005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002007}
2008
Guido van Rossuma110aa61994-08-29 12:50:44 +00002009/* Set the error appropriate to the given input error code (see errcode.h) */
2010
2011static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002012err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 PyObject *v, *w, *errtype, *errtext;
2015 PyObject *msg_obj = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002016 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 errtype = PyExc_SyntaxError;
2020 switch (err->error) {
2021 case E_ERROR:
2022 return;
2023 case E_SYNTAX:
2024 errtype = PyExc_IndentationError;
2025 if (err->expected == INDENT)
2026 msg = "expected an indented block";
2027 else if (err->token == INDENT)
2028 msg = "unexpected indent";
2029 else if (err->token == DEDENT)
2030 msg = "unexpected unindent";
2031 else {
2032 errtype = PyExc_SyntaxError;
2033 msg = "invalid syntax";
2034 }
2035 break;
2036 case E_TOKEN:
2037 msg = "invalid token";
2038 break;
2039 case E_EOFS:
2040 msg = "EOF while scanning triple-quoted string literal";
2041 break;
2042 case E_EOLS:
2043 msg = "EOL while scanning string literal";
2044 break;
2045 case E_INTR:
2046 if (!PyErr_Occurred())
2047 PyErr_SetNone(PyExc_KeyboardInterrupt);
2048 goto cleanup;
2049 case E_NOMEM:
2050 PyErr_NoMemory();
2051 goto cleanup;
2052 case E_EOF:
2053 msg = "unexpected EOF while parsing";
2054 break;
2055 case E_TABSPACE:
2056 errtype = PyExc_TabError;
2057 msg = "inconsistent use of tabs and spaces in indentation";
2058 break;
2059 case E_OVERFLOW:
2060 msg = "expression too long";
2061 break;
2062 case E_DEDENT:
2063 errtype = PyExc_IndentationError;
2064 msg = "unindent does not match any outer indentation level";
2065 break;
2066 case E_TOODEEP:
2067 errtype = PyExc_IndentationError;
2068 msg = "too many levels of indentation";
2069 break;
2070 case E_DECODE: {
2071 PyObject *type, *value, *tb;
2072 PyErr_Fetch(&type, &value, &tb);
2073 msg = "unknown decode error";
2074 if (value != NULL)
2075 msg_obj = PyObject_Str(value);
2076 Py_XDECREF(type);
2077 Py_XDECREF(value);
2078 Py_XDECREF(tb);
2079 break;
2080 }
2081 case E_LINECONT:
2082 msg = "unexpected character after line continuation character";
2083 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 case E_IDENTIFIER:
2086 msg = "invalid character in identifier";
2087 break;
2088 default:
2089 fprintf(stderr, "error=%d\n", err->error);
2090 msg = "unknown parsing error";
2091 break;
2092 }
2093 /* err->text may not be UTF-8 in case of decoding errors.
2094 Explicitly convert to an object. */
2095 if (!err->text) {
2096 errtext = Py_None;
2097 Py_INCREF(Py_None);
2098 } else {
2099 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2100 "replace");
2101 }
Victor Stinner2f2ed1f2010-10-16 13:42:53 +00002102 if (err->filename != NULL)
2103 filename = PyUnicode_DecodeFSDefault(err->filename);
2104 else {
2105 Py_INCREF(Py_None);
2106 filename = Py_None;
2107 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002108 if (filename != NULL)
2109 v = Py_BuildValue("(NiiN)", filename,
2110 err->lineno, err->offset, errtext);
2111 else
2112 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (v != NULL) {
2114 if (msg_obj)
2115 w = Py_BuildValue("(OO)", msg_obj, v);
2116 else
2117 w = Py_BuildValue("(sO)", msg, v);
2118 } else
2119 w = NULL;
2120 Py_XDECREF(v);
2121 PyErr_SetObject(errtype, w);
2122 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002123cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 Py_XDECREF(msg_obj);
2125 if (err->text != NULL) {
2126 PyObject_FREE(err->text);
2127 err->text = NULL;
2128 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002129}
2130
2131/* Print fatal error message and abort */
2132
2133void
Tim Peters7c321a82002-07-09 02:57:01 +00002134Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 fprintf(stderr, "Fatal Python error: %s\n", msg);
2137 fflush(stderr); /* it helps in Windows debug build */
2138 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002139 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002141#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 {
2143 size_t len = strlen(msg);
2144 WCHAR* buffer;
2145 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 /* Convert the message to wchar_t. This uses a simple one-to-one
2148 conversion, assuming that the this error message actually uses ASCII
2149 only. If this ceases to be true, we will have to convert. */
2150 buffer = alloca( (len+1) * (sizeof *buffer));
2151 for( i=0; i<=len; ++i)
2152 buffer[i] = msg[i];
2153 OutputDebugStringW(L"Fatal Python error: ");
2154 OutputDebugStringW(buffer);
2155 OutputDebugStringW(L"\n");
2156 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002157#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002159#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002160#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002162}
2163
2164/* Clean up and exit */
2165
Guido van Rossuma110aa61994-08-29 12:50:44 +00002166#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002167#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002168#endif
2169
Collin Winter670e6922007-03-21 02:57:17 +00002170static void (*pyexitfunc)(void) = NULL;
2171/* For the atexit module. */
2172void _Py_PyAtExit(void (*func)(void))
2173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002175}
2176
2177static void
2178call_py_exitfuncs(void)
2179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 if (pyexitfunc == NULL)
2181 return;
Collin Winter670e6922007-03-21 02:57:17 +00002182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 (*pyexitfunc)();
2184 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002185}
2186
Antoine Pitrou011bd622009-10-20 21:52:47 +00002187/* Wait until threading._shutdown completes, provided
2188 the threading module was imported in the first place.
2189 The shutdown routine will wait until all non-daemon
2190 "threading" threads have completed. */
2191static void
2192wait_for_thread_shutdown(void)
2193{
2194#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 PyObject *result;
2196 PyThreadState *tstate = PyThreadState_GET();
2197 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2198 "threading");
2199 if (threading == NULL) {
2200 /* threading not imported */
2201 PyErr_Clear();
2202 return;
2203 }
2204 result = PyObject_CallMethod(threading, "_shutdown", "");
2205 if (result == NULL) {
2206 PyErr_WriteUnraisable(threading);
2207 }
2208 else {
2209 Py_DECREF(result);
2210 }
2211 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002212#endif
2213}
2214
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002215#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002216static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002217static int nexitfuncs = 0;
2218
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002219int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 if (nexitfuncs >= NEXITFUNCS)
2222 return -1;
2223 exitfuncs[nexitfuncs++] = func;
2224 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002225}
2226
Guido van Rossumcc283f51997-08-05 02:22:03 +00002227static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002228call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 while (nexitfuncs > 0)
2231 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 fflush(stdout);
2234 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002235}
2236
2237void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002238Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002243}
2244
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002245static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002246initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002247{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002248#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002250#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002251#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002253#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002254#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002256#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002258}
2259
Guido van Rossum7433b121997-02-14 19:45:36 +00002260
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002261/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2262 *
2263 * All of the code in this function must only use async-signal-safe functions,
2264 * listed at `man 7 signal` or
2265 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2266 */
2267void
2268_Py_RestoreSignals(void)
2269{
2270#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002272#endif
2273#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002275#endif
2276#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002278#endif
2279}
2280
2281
Guido van Rossum7433b121997-02-14 19:45:36 +00002282/*
2283 * The file descriptor fd is considered ``interactive'' if either
2284 * a) isatty(fd) is TRUE, or
2285 * b) the -i flag was given, and the filename associated with
2286 * the descriptor is NULL or "<stdin>" or "???".
2287 */
2288int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002289Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 if (isatty((int)fileno(fp)))
2292 return 1;
2293 if (!Py_InteractiveFlag)
2294 return 0;
2295 return (filename == NULL) ||
2296 (strcmp(filename, "<stdin>") == 0) ||
2297 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002298}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002299
2300
Tim Petersd08e3822003-04-17 15:24:21 +00002301#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002302#if defined(WIN32) && defined(_MSC_VER)
2303
2304/* Stack checking for Microsoft C */
2305
2306#include <malloc.h>
2307#include <excpt.h>
2308
Fred Drakee8de31c2000-08-31 05:38:39 +00002309/*
2310 * Return non-zero when we run out of memory on the stack; zero otherwise.
2311 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002312int
Fred Drake399739f2000-08-31 05:52:44 +00002313PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 __try {
2316 /* alloca throws a stack overflow exception if there's
2317 not enough space left on the stack */
2318 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2319 return 0;
2320 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2321 EXCEPTION_EXECUTE_HANDLER :
2322 EXCEPTION_CONTINUE_SEARCH) {
2323 int errcode = _resetstkoflw();
2324 if (errcode == 0)
2325 {
2326 Py_FatalError("Could not reset the stack!");
2327 }
2328 }
2329 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002330}
2331
2332#endif /* WIN32 && _MSC_VER */
2333
2334/* Alternate implementations can be added here... */
2335
2336#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002337
2338
2339/* Wrappers around sigaction() or signal(). */
2340
2341PyOS_sighandler_t
2342PyOS_getsig(int sig)
2343{
2344#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 struct sigaction context;
2346 if (sigaction(sig, NULL, &context) == -1)
2347 return SIG_ERR;
2348 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002349#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002351/* Special signal handling for the secure CRT in Visual Studio 2005 */
2352#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 switch (sig) {
2354 /* Only these signals are valid */
2355 case SIGINT:
2356 case SIGILL:
2357 case SIGFPE:
2358 case SIGSEGV:
2359 case SIGTERM:
2360 case SIGBREAK:
2361 case SIGABRT:
2362 break;
2363 /* Don't call signal() with other values or it will assert */
2364 default:
2365 return SIG_ERR;
2366 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002367#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 handler = signal(sig, SIG_IGN);
2369 if (handler != SIG_ERR)
2370 signal(sig, handler);
2371 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002372#endif
2373}
2374
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002375/*
2376 * All of the code in this function must only use async-signal-safe functions,
2377 * listed at `man 7 signal` or
2378 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2379 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002380PyOS_sighandler_t
2381PyOS_setsig(int sig, PyOS_sighandler_t handler)
2382{
2383#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 /* Some code in Modules/signalmodule.c depends on sigaction() being
2385 * used here if HAVE_SIGACTION is defined. Fix that if this code
2386 * changes to invalidate that assumption.
2387 */
2388 struct sigaction context, ocontext;
2389 context.sa_handler = handler;
2390 sigemptyset(&context.sa_mask);
2391 context.sa_flags = 0;
2392 if (sigaction(sig, &context, &ocontext) == -1)
2393 return SIG_ERR;
2394 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002395#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 PyOS_sighandler_t oldhandler;
2397 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002398#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002400#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002402#endif
2403}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002404
2405/* Deprecated C API functions still provided for binary compatiblity */
2406
2407#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002408PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002412}
2413
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002414#undef PyParser_SimpleParseString
2415PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002416PyParser_SimpleParseString(const char *str, int start)
2417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002419}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002420
2421#undef PyRun_AnyFile
2422PyAPI_FUNC(int)
2423PyRun_AnyFile(FILE *fp, const char *name)
2424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002426}
2427
2428#undef PyRun_AnyFileEx
2429PyAPI_FUNC(int)
2430PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002433}
2434
2435#undef PyRun_AnyFileFlags
2436PyAPI_FUNC(int)
2437PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002440}
2441
2442#undef PyRun_File
2443PyAPI_FUNC(PyObject *)
2444PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002447}
2448
2449#undef PyRun_FileEx
2450PyAPI_FUNC(PyObject *)
2451PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002454}
2455
2456#undef PyRun_FileFlags
2457PyAPI_FUNC(PyObject *)
2458PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002462}
2463
2464#undef PyRun_SimpleFile
2465PyAPI_FUNC(int)
2466PyRun_SimpleFile(FILE *f, const char *p)
2467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002469}
2470
2471#undef PyRun_SimpleFileEx
2472PyAPI_FUNC(int)
2473PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002476}
2477
2478
2479#undef PyRun_String
2480PyAPI_FUNC(PyObject *)
2481PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002484}
2485
2486#undef PyRun_SimpleString
2487PyAPI_FUNC(int)
2488PyRun_SimpleString(const char *s)
2489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002491}
2492
2493#undef Py_CompileString
2494PyAPI_FUNC(PyObject *)
2495Py_CompileString(const char *str, const char *p, int s)
2496{
Georg Brandl8334fd92010-12-04 10:26:46 +00002497 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2498}
2499
2500#undef Py_CompileStringFlags
2501PyAPI_FUNC(PyObject *)
2502Py_CompileStringFlags(const char *str, const char *p, int s,
2503 PyCompilerFlags *flags)
2504{
2505 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002506}
2507
2508#undef PyRun_InteractiveOne
2509PyAPI_FUNC(int)
2510PyRun_InteractiveOne(FILE *f, const char *p)
2511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002513}
2514
2515#undef PyRun_InteractiveLoop
2516PyAPI_FUNC(int)
2517PyRun_InteractiveLoop(FILE *f, const char *p)
2518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002520}
2521
2522#ifdef __cplusplus
2523}
2524#endif