blob: 084db12f635e12ea6dd60f5ebc0c2aa2bebdd2cf [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
Neal Norwitz2bad9702007-08-27 06:19:22 +0000335static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000336flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 PyObject *fout = PySys_GetObject("stdout");
339 PyObject *ferr = PySys_GetObject("stderr");
340 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (fout != NULL && fout != Py_None) {
343 tmp = PyObject_CallMethod(fout, "flush", "");
344 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000345 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 else
347 Py_DECREF(tmp);
348 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000349
Victor Stinner9467b212010-05-14 00:59:09 +0000350 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 tmp = PyObject_CallMethod(ferr, "flush", "");
352 if (tmp == NULL)
353 PyErr_Clear();
354 else
355 Py_DECREF(tmp);
356 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000357}
358
Guido van Rossum25ce5661997-08-02 03:10:38 +0000359/* Undo the effect of Py_Initialize().
360
361 Beware: if multiple interpreter and/or thread states exist, these
362 are not wiped out; only the current thread and interpreter state
363 are deleted. But since everything else is deleted, those other
364 interpreter and thread states should no longer be used.
365
366 (XXX We should do better, e.g. wipe out all interpreters and
367 threads.)
368
369 Locking: as above.
370
371*/
372
373void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000374Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 PyInterpreterState *interp;
377 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (!initialized)
380 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 /* The interpreter is still entirely intact at this point, and the
385 * exit funcs may be relying on that. In particular, if some thread
386 * or exit func is still waiting to do an import, the import machinery
387 * expects Py_IsInitialized() to return true. So don't say the
388 * interpreter is uninitialized until after the exit funcs have run.
389 * Note that Threading.py uses an exit func to do a join on all the
390 * threads created thru it, so this also protects pending imports in
391 * the threads created via Threading.
392 */
393 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Get current thread state and interpreter pointer */
396 tstate = PyThreadState_GET();
397 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000398
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200399 /* Remaining threads (e.g. daemon threads) will automatically exit
400 after taking the GIL (in PyEval_RestoreThread()). */
401 _Py_Finalizing = tstate;
402 initialized = 0;
403
404 /* Flush stdout+stderr */
405 flush_std_files();
406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 /* Disable signal handling */
408 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 /* Clear type lookup cache */
411 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 /* Collect garbage. This may call finalizers; it's nice to call these
414 * before all modules are destroyed.
415 * XXX If a __del__ or weakref callback is triggered here, and tries to
416 * XXX import a module, bad things can happen, because Python no
417 * XXX longer believes it's initialized.
418 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
419 * XXX is easy to provoke that way. I've also seen, e.g.,
420 * XXX Exception exceptions.ImportError: 'No module named sha'
421 * XXX in <function callback at 0x008F5718> ignored
422 * XXX but I'm unclear on exactly how that one happens. In any case,
423 * XXX I haven't seen a real-life report of either of these.
424 */
425 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000426#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 /* With COUNT_ALLOCS, it helps to run GC multiple times:
428 each collection might release some types from the type
429 list, so they become garbage. */
430 while (PyGC_Collect() > 0)
431 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000432#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000433 /* We run this while most interpreter state is still alive, so that
434 debug information can be printed out */
435 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 /* Destroy all modules */
438 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 /* Flush stdout+stderr (again, in case more was printed) */
441 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* Collect final garbage. This disposes of cycles created by
444 * new-style class definitions, for example.
445 * XXX This is disabled because it caused too many problems. If
446 * XXX a __del__ or weakref callback triggers here, Python code has
447 * XXX a hard time running, because even the sys module has been
448 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
449 * XXX One symptom is a sequence of information-free messages
450 * XXX coming from threads (if a __del__ or callback is invoked,
451 * XXX other threads can execute too, and any exception they encounter
452 * XXX triggers a comedy of errors as subsystem after subsystem
453 * XXX fails to find what it *expects* to find in sys to help report
454 * XXX the exception and consequent unexpected failures). I've also
455 * XXX seen segfaults then, after adding print statements to the
456 * XXX Python code getting called.
457 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000458#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000460#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
463 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000466#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000468#endif
469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000471
Tim Peters9cf25ce2003-04-17 15:21:01 +0000472#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 /* Display all objects still alive -- this can invoke arbitrary
474 * __repr__ overrides, so requires a mostly-intact interpreter.
475 * Alas, a lot of stuff may still be alive now that will be cleaned
476 * up later.
477 */
478 if (Py_GETENV("PYTHONDUMPREFS"))
479 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000480#endif /* Py_TRACE_REFS */
481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 /* Clear interpreter state */
483 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* Now we decref the exception classes. After this point nothing
486 can raise an exception. That's okay, because each Fini() method
487 below has been checked to make sure no exceptions are ever
488 raised.
489 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000494#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000496#endif /* WITH_THREAD */
497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 /* Delete current thread */
499 PyThreadState_Swap(NULL);
500 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 /* Sundry finalizers */
503 PyMethod_Fini();
504 PyFrame_Fini();
505 PyCFunction_Fini();
506 PyTuple_Fini();
507 PyList_Fini();
508 PySet_Fini();
509 PyBytes_Fini();
510 PyByteArray_Fini();
511 PyLong_Fini();
512 PyFloat_Fini();
513 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 /* Cleanup Unicode implementation */
516 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000519 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 free((char*)Py_FileSystemDefaultEncoding);
521 Py_FileSystemDefaultEncoding = NULL;
522 }
Christian Heimesc8967002007-11-30 10:18:26 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 /* XXX Still allocated:
525 - various static ad-hoc pointers to interned strings
526 - int and float free list blocks
527 - whatever various modules and libraries allocate
528 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000531
Tim Peters269b2a62003-04-17 19:52:29 +0000532#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 /* Display addresses (& refcnts) of all objects still alive.
534 * An address can be used to find the repr of the object, printed
535 * above by _Py_PrintReferences.
536 */
537 if (Py_GETENV("PYTHONDUMPREFS"))
538 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000539#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000540#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 if (Py_GETENV("PYTHONMALLOCSTATS"))
542 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000543#endif
544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000546}
547
548/* Create and initialize a new interpreter and thread, and return the
549 new thread. This requires that Py_Initialize() has been called
550 first.
551
552 Unsuccessful initialization yields a NULL pointer. Note that *no*
553 exception information is available even in this case -- the
554 exception information is held in the thread, and there is no
555 thread.
556
557 Locking: as above.
558
559*/
560
561PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000562Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 PyInterpreterState *interp;
565 PyThreadState *tstate, *save_tstate;
566 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 if (!initialized)
569 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 interp = PyInterpreterState_New();
572 if (interp == NULL)
573 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 tstate = PyThreadState_New(interp);
576 if (tstate == NULL) {
577 PyInterpreterState_Delete(interp);
578 return NULL;
579 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 interp->modules = PyDict_New();
586 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000587
Victor Stinner49d3f252010-10-17 01:24:53 +0000588 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (bimod != NULL) {
590 interp->builtins = PyModule_GetDict(bimod);
591 if (interp->builtins == NULL)
592 goto handle_error;
593 Py_INCREF(interp->builtins);
594 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 /* initialize builtin exceptions */
597 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000598
Victor Stinner49d3f252010-10-17 01:24:53 +0000599 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (bimod != NULL && sysmod != NULL) {
601 PyObject *pstderr;
602 interp->sysdict = PyModule_GetDict(sysmod);
603 if (interp->sysdict == NULL)
604 goto handle_error;
605 Py_INCREF(interp->sysdict);
606 PySys_SetPath(Py_GetPath());
607 PyDict_SetItemString(interp->sysdict, "modules",
608 interp->modules);
609 /* Set up a preliminary stderr printer until we have enough
610 infrastructure for the io module in place. */
611 pstderr = PyFile_NewStdPrinter(fileno(stderr));
612 if (pstderr == NULL)
613 Py_FatalError("Py_Initialize: can't set preliminary stderr");
614 PySys_SetObject("stderr", pstderr);
615 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000616 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 _PyImportHooks_Init();
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200619
620 if (initfsencoding(interp) < 0)
621 goto handle_error;
622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 if (initstdio() < 0)
624 Py_FatalError(
625 "Py_Initialize: can't initialize sys standard streams");
626 initmain();
627 if (!Py_NoSiteFlag)
628 initsite();
629 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 if (!PyErr_Occurred())
632 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633
Thomas Wouters89f507f2006-12-13 04:49:30 +0000634handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000636
Victor Stinner11889352011-04-27 00:20:27 +0200637 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyThreadState_Clear(tstate);
639 PyThreadState_Swap(save_tstate);
640 PyThreadState_Delete(tstate);
641 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644}
645
646/* Delete an interpreter and its last thread. This requires that the
647 given thread state is current, that the thread has no remaining
648 frames, and that it is its interpreter's only remaining thread.
649 It is a fatal error to violate these constraints.
650
651 (Py_Finalize() doesn't have these constraints -- it zaps
652 everything, regardless.)
653
654 Locking: as above.
655
656*/
657
658void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000659Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 if (tstate != PyThreadState_GET())
664 Py_FatalError("Py_EndInterpreter: thread is not current");
665 if (tstate->frame != NULL)
666 Py_FatalError("Py_EndInterpreter: thread still has a frame");
667 if (tstate != interp->tstate_head || tstate->next != NULL)
668 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyImport_Cleanup();
671 PyInterpreterState_Clear(interp);
672 PyThreadState_Swap(NULL);
673 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000674}
675
Martin v. Löwis790465f2008-04-05 20:41:37 +0000676static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000677
678void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000679Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 if (pn && *pn)
682 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000683}
684
Martin v. Löwis790465f2008-04-05 20:41:37 +0000685wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000686Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000689}
690
Martin v. Löwis790465f2008-04-05 20:41:37 +0000691static wchar_t *default_home = NULL;
692static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000693
694void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000695Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000698}
699
Martin v. Löwis790465f2008-04-05 20:41:37 +0000700wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000701Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 wchar_t *home = default_home;
704 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
705 char* chome = Py_GETENV("PYTHONHOME");
706 if (chome) {
707 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
708 if (r != (size_t)-1 && r <= PATH_MAX)
709 home = env_home;
710 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 }
713 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000714}
715
Guido van Rossum6135a871995-01-09 17:53:26 +0000716/* Create __main__ module */
717
718static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000719initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 PyObject *m, *d;
722 m = PyImport_AddModule("__main__");
723 if (m == NULL)
724 Py_FatalError("can't create __main__ module");
725 d = PyModule_GetDict(m);
726 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
727 PyObject *bimod = PyImport_ImportModule("builtins");
728 if (bimod == NULL ||
729 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
730 Py_FatalError("can't add __builtins__ to __main__");
731 Py_DECREF(bimod);
732 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000733}
734
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200735static int
736initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000737{
738 PyObject *codec;
739#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000740 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000741
Victor Stinner7f84ab52010-06-11 00:36:33 +0000742 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000743 /* On Unix, set the file system encoding according to the
744 user's preference, if the CODESET names a well-known
745 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000746 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000747 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000748 if (codeset == NULL)
749 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000750
Victor Stinnere4743092010-10-19 00:05:51 +0000751 Py_FileSystemDefaultEncoding = codeset;
752 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200753 interp->fscodec_initialized = 1;
754 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000755 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000756#endif
757
758 /* the encoding is mbcs, utf-8 or ascii */
759 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
760 if (!codec) {
761 /* Such error can only occurs in critical situations: no more
762 * memory, import a module of the standard library failed,
763 * etc. */
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200764 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000765 }
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200766 Py_DECREF(codec);
767 interp->fscodec_initialized = 1;
768 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000769}
770
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000771/* Import the site module (not into __main__ though) */
772
773static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000774initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 PyObject *m;
777 m = PyImport_ImportModule("site");
778 if (m == NULL) {
779 PyErr_Print();
780 Py_Finalize();
781 exit(1);
782 }
783 else {
784 Py_DECREF(m);
785 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000786}
787
Antoine Pitrou05608432009-01-09 18:53:14 +0000788static PyObject*
789create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 int fd, int write_mode, char* name,
791 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
794 const char* mode;
Victor Stinner02bfdb32011-02-23 12:10:23 +0000795 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyObject *line_buffering;
797 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 /* stdin is always opened in buffered mode, first because it shouldn't
800 make a difference in common use cases, second because TextIOWrapper
801 depends on the presence of a read1() method which only exists on
802 buffered streams.
803 */
804 if (Py_UnbufferedStdioFlag && write_mode)
805 buffering = 0;
806 else
807 buffering = -1;
808 if (write_mode)
809 mode = "wb";
810 else
811 mode = "rb";
812 buf = PyObject_CallMethod(io, "open", "isiOOOi",
813 fd, mode, buffering,
814 Py_None, Py_None, Py_None, 0);
815 if (buf == NULL)
816 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (buffering) {
819 raw = PyObject_GetAttrString(buf, "raw");
820 if (raw == NULL)
821 goto error;
822 }
823 else {
824 raw = buf;
825 Py_INCREF(raw);
826 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 text = PyUnicode_FromString(name);
829 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
830 goto error;
831 res = PyObject_CallMethod(raw, "isatty", "");
832 if (res == NULL)
833 goto error;
834 isatty = PyObject_IsTrue(res);
835 Py_DECREF(res);
836 if (isatty == -1)
837 goto error;
838 if (isatty || Py_UnbufferedStdioFlag)
839 line_buffering = Py_True;
840 else
841 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 Py_CLEAR(raw);
844 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000845
Victor Stinner02bfdb32011-02-23 12:10:23 +0000846 newline = "\n";
847#ifdef MS_WINDOWS
848 if (!write_mode) {
849 /* translate \r\n to \n for sys.stdin on Windows */
850 newline = NULL;
851 }
852#endif
853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
855 buf, encoding, errors,
Victor Stinner02bfdb32011-02-23 12:10:23 +0000856 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 Py_CLEAR(buf);
858 if (stream == NULL)
859 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 if (write_mode)
862 mode = "w";
863 else
864 mode = "r";
865 text = PyUnicode_FromString(mode);
866 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
867 goto error;
868 Py_CLEAR(text);
869 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000870
871error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 Py_XDECREF(buf);
873 Py_XDECREF(stream);
874 Py_XDECREF(text);
875 Py_XDECREF(raw);
876 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000877}
878
Georg Brandl1a3284e2007-12-02 09:40:06 +0000879/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000880static int
881initstdio(void)
882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 PyObject *iomod = NULL, *wrapper;
884 PyObject *bimod = NULL;
885 PyObject *m;
886 PyObject *std = NULL;
887 int status = 0, fd;
888 PyObject * encoding_attr;
889 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* Hack to avoid a nasty recursion issue when Python is invoked
892 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
893 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
894 goto error;
895 }
896 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
899 goto error;
900 }
901 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 if (!(bimod = PyImport_ImportModule("builtins"))) {
904 goto error;
905 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 if (!(iomod = PyImport_ImportModule("io"))) {
908 goto error;
909 }
910 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
911 goto error;
912 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Set builtins.open */
915 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000916 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 goto error;
918 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000919 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 encoding = Py_GETENV("PYTHONIOENCODING");
922 errors = NULL;
923 if (encoding) {
924 encoding = strdup(encoding);
925 errors = strchr(encoding, ':');
926 if (errors) {
927 *errors = '\0';
928 errors++;
929 }
930 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 /* Set sys.stdin */
933 fd = fileno(stdin);
934 /* Under some conditions stdin, stdout and stderr may not be connected
935 * and fileno() may point to an invalid file descriptor. For example
936 * GUI apps don't have valid standard streams by default.
937 */
938 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000939#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 std = Py_None;
941 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000942#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000944#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 }
946 else {
947 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
948 if (std == NULL)
949 goto error;
950 } /* if (fd < 0) */
951 PySys_SetObject("__stdin__", std);
952 PySys_SetObject("stdin", std);
953 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* Set sys.stdout */
956 fd = fileno(stdout);
957 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000958#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 std = Py_None;
960 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000961#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000963#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 }
965 else {
966 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
967 if (std == NULL)
968 goto error;
969 } /* if (fd < 0) */
970 PySys_SetObject("__stdout__", std);
971 PySys_SetObject("stdout", std);
972 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000973
Guido van Rossum98297ee2007-11-06 21:34:58 +0000974#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 /* Set sys.stderr, replaces the preliminary stderr */
976 fd = fileno(stderr);
977 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000978#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 std = Py_None;
980 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000981#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000983#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 }
985 else {
986 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
987 if (std == NULL)
988 goto error;
989 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 /* Same as hack above, pre-import stderr's codec to avoid recursion
992 when import.c tries to write to stderr in verbose mode. */
993 encoding_attr = PyObject_GetAttrString(std, "encoding");
994 if (encoding_attr != NULL) {
995 const char * encoding;
996 encoding = _PyUnicode_AsString(encoding_attr);
997 if (encoding != NULL) {
998 _PyCodec_Lookup(encoding);
999 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001000 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 }
1002 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PySys_SetObject("__stderr__", std);
1005 PySys_SetObject("stderr", std);
1006 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001007#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001010 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 status = -1;
1012 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (encoding)
1015 free(encoding);
1016 Py_XDECREF(bimod);
1017 Py_XDECREF(iomod);
1018 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001019}
1020
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001021/* Parse input from a file and execute it */
1022
1023int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001024PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (filename == NULL)
1028 filename = "???";
1029 if (Py_FdIsInteractive(fp, filename)) {
1030 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1031 if (closeit)
1032 fclose(fp);
1033 return err;
1034 }
1035 else
1036 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001037}
1038
1039int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001040PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 PyObject *v;
1043 int ret;
1044 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 if (flags == NULL) {
1047 flags = &local_flags;
1048 local_flags.cf_flags = 0;
1049 }
1050 v = PySys_GetObject("ps1");
1051 if (v == NULL) {
1052 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1053 Py_XDECREF(v);
1054 }
1055 v = PySys_GetObject("ps2");
1056 if (v == NULL) {
1057 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1058 Py_XDECREF(v);
1059 }
1060 for (;;) {
1061 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1062 PRINT_TOTAL_REFS();
1063 if (ret == E_EOF)
1064 return 0;
1065 /*
1066 if (ret == E_NOMEM)
1067 return -1;
1068 */
1069 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001070}
1071
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001072/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001073static int PARSER_FLAGS(PyCompilerFlags *flags)
1074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 int parser_flags = 0;
1076 if (!flags)
1077 return 0;
1078 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1079 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1080 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1081 parser_flags |= PyPARSE_IGNORE_COOKIE;
1082 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1083 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1084 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001085}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001086
Thomas Wouters89f507f2006-12-13 04:49:30 +00001087#if 0
1088/* Keep an example of flags with future keyword support. */
1089#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1091 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1092 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1093 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001094#endif
1095
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001096int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001097PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyObject *m, *d, *v, *w, *oenc = NULL;
1100 mod_ty mod;
1101 PyArena *arena;
1102 char *ps1 = "", *ps2 = "", *enc = NULL;
1103 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 if (fp == stdin) {
1106 /* Fetch encoding from sys.stdin */
1107 v = PySys_GetObject("stdin");
1108 if (v == NULL || v == Py_None)
1109 return -1;
1110 oenc = PyObject_GetAttrString(v, "encoding");
1111 if (!oenc)
1112 return -1;
1113 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001114 if (enc == NULL)
1115 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 }
1117 v = PySys_GetObject("ps1");
1118 if (v != NULL) {
1119 v = PyObject_Str(v);
1120 if (v == NULL)
1121 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001122 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001124 if (ps1 == NULL) {
1125 PyErr_Clear();
1126 ps1 = "";
1127 }
1128 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 }
1130 w = PySys_GetObject("ps2");
1131 if (w != NULL) {
1132 w = PyObject_Str(w);
1133 if (w == NULL)
1134 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001135 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001137 if (ps2 == NULL) {
1138 PyErr_Clear();
1139 ps2 = "";
1140 }
1141 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 }
1143 arena = PyArena_New();
1144 if (arena == NULL) {
1145 Py_XDECREF(v);
1146 Py_XDECREF(w);
1147 Py_XDECREF(oenc);
1148 return -1;
1149 }
1150 mod = PyParser_ASTFromFile(fp, filename, enc,
1151 Py_single_input, ps1, ps2,
1152 flags, &errcode, arena);
1153 Py_XDECREF(v);
1154 Py_XDECREF(w);
1155 Py_XDECREF(oenc);
1156 if (mod == NULL) {
1157 PyArena_Free(arena);
1158 if (errcode == E_EOF) {
1159 PyErr_Clear();
1160 return E_EOF;
1161 }
1162 PyErr_Print();
1163 return -1;
1164 }
1165 m = PyImport_AddModule("__main__");
1166 if (m == NULL) {
1167 PyArena_Free(arena);
1168 return -1;
1169 }
1170 d = PyModule_GetDict(m);
1171 v = run_mod(mod, filename, d, d, flags, arena);
1172 PyArena_Free(arena);
1173 flush_io();
1174 if (v == NULL) {
1175 PyErr_Print();
1176 return -1;
1177 }
1178 Py_DECREF(v);
1179 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001180}
1181
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001182/* Check whether a file maybe a pyc file: Look at the extension,
1183 the file type, and, if we may close it, at the first few bytes. */
1184
1185static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001186maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1189 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 /* Only look into the file if we are allowed to close it, since
1192 it then should also be seekable. */
1193 if (closeit) {
1194 /* Read only two bytes of the magic. If the file was opened in
1195 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1196 be read as they are on disk. */
1197 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1198 unsigned char buf[2];
1199 /* Mess: In case of -x, the stream is NOT at its start now,
1200 and ungetc() was used to push back the first newline,
1201 which makes the current stream position formally undefined,
1202 and a x-platform nightmare.
1203 Unfortunately, we have no direct way to know whether -x
1204 was specified. So we use a terrible hack: if the current
1205 stream position is not 0, we assume -x was specified, and
1206 give up. Bug 132850 on SourceForge spells out the
1207 hopelessness of trying anything else (fseek and ftell
1208 don't work predictably x-platform for text-mode files).
1209 */
1210 int ispyc = 0;
1211 if (ftell(fp) == 0) {
1212 if (fread(buf, 1, 2, fp) == 2 &&
1213 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1214 ispyc = 1;
1215 rewind(fp);
1216 }
1217 return ispyc;
1218 }
1219 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001220}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001221
Guido van Rossum0df002c2000-08-27 19:21:52 +00001222int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001223PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 PyObject *m, *d, *v;
1227 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001228 int set_file_name = 0, ret;
1229 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 m = PyImport_AddModule("__main__");
1232 if (m == NULL)
1233 return -1;
1234 d = PyModule_GetDict(m);
1235 if (PyDict_GetItemString(d, "__file__") == NULL) {
1236 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001237 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (f == NULL)
1239 return -1;
1240 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1241 Py_DECREF(f);
1242 return -1;
1243 }
1244 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1245 return -1;
1246 set_file_name = 1;
1247 Py_DECREF(f);
1248 }
1249 len = strlen(filename);
1250 ext = filename + len - (len > 4 ? 4 : 0);
1251 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1252 /* Try to run a pyc file. First, re-open in binary */
1253 if (closeit)
1254 fclose(fp);
1255 if ((fp = fopen(filename, "rb")) == NULL) {
1256 fprintf(stderr, "python: Can't reopen .pyc file\n");
1257 ret = -1;
1258 goto done;
1259 }
1260 /* Turn on optimization if a .pyo file is given */
1261 if (strcmp(ext, ".pyo") == 0)
1262 Py_OptimizeFlag = 1;
1263 v = run_pyc_file(fp, filename, d, d, flags);
1264 } else {
1265 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1266 closeit, flags);
1267 }
1268 flush_io();
1269 if (v == NULL) {
1270 PyErr_Print();
1271 ret = -1;
1272 goto done;
1273 }
1274 Py_DECREF(v);
1275 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001276 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1278 PyErr_Clear();
1279 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001280}
1281
1282int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001283PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 PyObject *m, *d, *v;
1286 m = PyImport_AddModule("__main__");
1287 if (m == NULL)
1288 return -1;
1289 d = PyModule_GetDict(m);
1290 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1291 if (v == NULL) {
1292 PyErr_Print();
1293 return -1;
1294 }
1295 Py_DECREF(v);
1296 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001297}
1298
Barry Warsaw035574d1997-08-29 22:07:17 +00001299static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001300parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 long hold;
1304 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 /* old style errors */
1307 if (PyTuple_Check(err))
1308 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1309 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (! (v = PyObject_GetAttrString(err, "msg")))
1314 goto finally;
1315 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 if (!(v = PyObject_GetAttrString(err, "filename")))
1318 goto finally;
1319 if (v == Py_None)
1320 *filename = NULL;
1321 else if (! (*filename = _PyUnicode_AsString(v)))
1322 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 Py_DECREF(v);
1325 if (!(v = PyObject_GetAttrString(err, "lineno")))
1326 goto finally;
1327 hold = PyLong_AsLong(v);
1328 Py_DECREF(v);
1329 v = NULL;
1330 if (hold < 0 && PyErr_Occurred())
1331 goto finally;
1332 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 if (!(v = PyObject_GetAttrString(err, "offset")))
1335 goto finally;
1336 if (v == Py_None) {
1337 *offset = -1;
1338 Py_DECREF(v);
1339 v = NULL;
1340 } else {
1341 hold = PyLong_AsLong(v);
1342 Py_DECREF(v);
1343 v = NULL;
1344 if (hold < 0 && PyErr_Occurred())
1345 goto finally;
1346 *offset = (int)hold;
1347 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 if (!(v = PyObject_GetAttrString(err, "text")))
1350 goto finally;
1351 if (v == Py_None)
1352 *text = NULL;
1353 else if (!PyUnicode_Check(v) ||
1354 !(*text = _PyUnicode_AsString(v)))
1355 goto finally;
1356 Py_DECREF(v);
1357 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001358
1359finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 Py_XDECREF(v);
1361 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001362}
1363
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001364void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001365PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001368}
1369
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001370static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001371print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 char *nl;
1374 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001375 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1376 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 for (;;) {
1378 nl = strchr(text, '\n');
1379 if (nl == NULL || nl-text >= offset)
1380 break;
1381 offset -= (int)(nl+1-text);
1382 text = nl+1;
1383 }
1384 while (*text == ' ' || *text == '\t') {
1385 text++;
1386 offset--;
1387 }
1388 }
1389 PyFile_WriteString(" ", f);
1390 PyFile_WriteString(text, f);
1391 if (*text == '\0' || text[strlen(text)-1] != '\n')
1392 PyFile_WriteString("\n", f);
1393 if (offset == -1)
1394 return;
1395 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001396 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001399}
1400
Guido van Rossum66e8e862001-03-23 17:54:43 +00001401static void
1402handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 PyObject *exception, *value, *tb;
1405 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 if (Py_InspectFlag)
1408 /* Don't exit if -i flag was given. This flag is set to 0
1409 * when entering interactive mode for inspecting. */
1410 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyErr_Fetch(&exception, &value, &tb);
1413 fflush(stdout);
1414 if (value == NULL || value == Py_None)
1415 goto done;
1416 if (PyExceptionInstance_Check(value)) {
1417 /* The error code should be in the `code' attribute. */
1418 PyObject *code = PyObject_GetAttrString(value, "code");
1419 if (code) {
1420 Py_DECREF(value);
1421 value = code;
1422 if (value == Py_None)
1423 goto done;
1424 }
1425 /* If we failed to dig out the 'code' attribute,
1426 just let the else clause below print the error. */
1427 }
1428 if (PyLong_Check(value))
1429 exitcode = (int)PyLong_AsLong(value);
1430 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001431 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001432 if (sys_stderr != NULL && sys_stderr != Py_None) {
1433 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1434 } else {
1435 PyObject_Print(value, stderr, Py_PRINT_RAW);
1436 fflush(stderr);
1437 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 PySys_WriteStderr("\n");
1439 exitcode = 1;
1440 }
Tim Peterscf615b52003-04-19 18:47:02 +00001441 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 /* Restore and clear the exception info, in order to properly decref
1443 * the exception, value, and traceback. If we just exit instead,
1444 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1445 * some finalizers from running.
1446 */
1447 PyErr_Restore(exception, value, tb);
1448 PyErr_Clear();
1449 Py_Exit(exitcode);
1450 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001451}
1452
1453void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001454PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1459 handle_system_exit();
1460 }
1461 PyErr_Fetch(&exception, &v, &tb);
1462 if (exception == NULL)
1463 return;
1464 PyErr_NormalizeException(&exception, &v, &tb);
1465 if (tb == NULL) {
1466 tb = Py_None;
1467 Py_INCREF(tb);
1468 }
1469 PyException_SetTraceback(v, tb);
1470 if (exception == NULL)
1471 return;
1472 /* Now we know v != NULL too */
1473 if (set_sys_last_vars) {
1474 PySys_SetObject("last_type", exception);
1475 PySys_SetObject("last_value", v);
1476 PySys_SetObject("last_traceback", tb);
1477 }
1478 hook = PySys_GetObject("excepthook");
1479 if (hook) {
1480 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1481 PyObject *result = PyEval_CallObject(hook, args);
1482 if (result == NULL) {
1483 PyObject *exception2, *v2, *tb2;
1484 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1485 handle_system_exit();
1486 }
1487 PyErr_Fetch(&exception2, &v2, &tb2);
1488 PyErr_NormalizeException(&exception2, &v2, &tb2);
1489 /* It should not be possible for exception2 or v2
1490 to be NULL. However PyErr_Display() can't
1491 tolerate NULLs, so just be safe. */
1492 if (exception2 == NULL) {
1493 exception2 = Py_None;
1494 Py_INCREF(exception2);
1495 }
1496 if (v2 == NULL) {
1497 v2 = Py_None;
1498 Py_INCREF(v2);
1499 }
1500 fflush(stdout);
1501 PySys_WriteStderr("Error in sys.excepthook:\n");
1502 PyErr_Display(exception2, v2, tb2);
1503 PySys_WriteStderr("\nOriginal exception was:\n");
1504 PyErr_Display(exception, v, tb);
1505 Py_DECREF(exception2);
1506 Py_DECREF(v2);
1507 Py_XDECREF(tb2);
1508 }
1509 Py_XDECREF(result);
1510 Py_XDECREF(args);
1511 } else {
1512 PySys_WriteStderr("sys.excepthook is missing\n");
1513 PyErr_Display(exception, v, tb);
1514 }
1515 Py_XDECREF(exception);
1516 Py_XDECREF(v);
1517 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001518}
1519
Benjamin Petersone6528212008-07-15 15:32:09 +00001520static void
1521print_exception(PyObject *f, PyObject *value)
1522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 int err = 0;
1524 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (!PyExceptionInstance_Check(value)) {
1527 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1528 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1529 PyFile_WriteString(" found\n", f);
1530 return;
1531 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 Py_INCREF(value);
1534 fflush(stdout);
1535 type = (PyObject *) Py_TYPE(value);
1536 tb = PyException_GetTraceback(value);
1537 if (tb && tb != Py_None)
1538 err = PyTraceBack_Print(tb, f);
1539 if (err == 0 &&
1540 PyObject_HasAttrString(value, "print_file_and_line"))
1541 {
1542 PyObject *message;
1543 const char *filename, *text;
1544 int lineno, offset;
1545 if (!parse_syntax_error(value, &message, &filename,
1546 &lineno, &offset, &text))
1547 PyErr_Clear();
1548 else {
1549 char buf[10];
1550 PyFile_WriteString(" File \"", f);
1551 if (filename == NULL)
1552 PyFile_WriteString("<string>", f);
1553 else
1554 PyFile_WriteString(filename, f);
1555 PyFile_WriteString("\", line ", f);
1556 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1557 PyFile_WriteString(buf, f);
1558 PyFile_WriteString("\n", f);
1559 if (text != NULL)
1560 print_error_text(f, offset, text);
1561 Py_DECREF(value);
1562 value = message;
1563 /* Can't be bothered to check all those
1564 PyFile_WriteString() calls */
1565 if (PyErr_Occurred())
1566 err = -1;
1567 }
1568 }
1569 if (err) {
1570 /* Don't do anything else */
1571 }
1572 else {
1573 PyObject* moduleName;
1574 char* className;
1575 assert(PyExceptionClass_Check(type));
1576 className = PyExceptionClass_Name(type);
1577 if (className != NULL) {
1578 char *dot = strrchr(className, '.');
1579 if (dot != NULL)
1580 className = dot+1;
1581 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 moduleName = PyObject_GetAttrString(type, "__module__");
1584 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1585 {
1586 Py_DECREF(moduleName);
1587 err = PyFile_WriteString("<unknown>", f);
1588 }
1589 else {
1590 char* modstr = _PyUnicode_AsString(moduleName);
1591 if (modstr && strcmp(modstr, "builtins"))
1592 {
1593 err = PyFile_WriteString(modstr, f);
1594 err += PyFile_WriteString(".", f);
1595 }
1596 Py_DECREF(moduleName);
1597 }
1598 if (err == 0) {
1599 if (className == NULL)
1600 err = PyFile_WriteString("<unknown>", f);
1601 else
1602 err = PyFile_WriteString(className, f);
1603 }
1604 }
1605 if (err == 0 && (value != Py_None)) {
1606 PyObject *s = PyObject_Str(value);
1607 /* only print colon if the str() of the
1608 object is not the empty string
1609 */
1610 if (s == NULL)
1611 err = -1;
1612 else if (!PyUnicode_Check(s) ||
1613 PyUnicode_GetSize(s) != 0)
1614 err = PyFile_WriteString(": ", f);
1615 if (err == 0)
1616 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1617 Py_XDECREF(s);
1618 }
1619 /* try to write a newline in any case */
1620 err += PyFile_WriteString("\n", f);
1621 Py_XDECREF(tb);
1622 Py_DECREF(value);
1623 /* If an error happened here, don't show it.
1624 XXX This is wrong, but too many callers rely on this behavior. */
1625 if (err != 0)
1626 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001627}
1628
1629static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 "\nThe above exception was the direct cause "
1631 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001632
1633static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 "\nDuring handling of the above exception, "
1635 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001636
1637static void
1638print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 int err = 0, res;
1641 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (seen != NULL) {
1644 /* Exception chaining */
1645 if (PySet_Add(seen, value) == -1)
1646 PyErr_Clear();
1647 else if (PyExceptionInstance_Check(value)) {
1648 cause = PyException_GetCause(value);
1649 context = PyException_GetContext(value);
1650 if (cause) {
1651 res = PySet_Contains(seen, cause);
1652 if (res == -1)
1653 PyErr_Clear();
1654 if (res == 0) {
1655 print_exception_recursive(
1656 f, cause, seen);
1657 err |= PyFile_WriteString(
1658 cause_message, f);
1659 }
1660 }
1661 else if (context) {
1662 res = PySet_Contains(seen, context);
1663 if (res == -1)
1664 PyErr_Clear();
1665 if (res == 0) {
1666 print_exception_recursive(
1667 f, context, seen);
1668 err |= PyFile_WriteString(
1669 context_message, f);
1670 }
1671 }
1672 Py_XDECREF(context);
1673 Py_XDECREF(cause);
1674 }
1675 }
1676 print_exception(f, value);
1677 if (err != 0)
1678 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001679}
1680
Thomas Wouters477c8d52006-05-27 19:21:47 +00001681void
1682PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 PyObject *seen;
1685 PyObject *f = PySys_GetObject("stderr");
1686 if (f == Py_None) {
1687 /* pass */
1688 }
1689 else if (f == NULL) {
1690 _PyObject_Dump(value);
1691 fprintf(stderr, "lost sys.stderr\n");
1692 }
1693 else {
1694 /* We choose to ignore seen being possibly NULL, and report
1695 at least the main exception (it could be a MemoryError).
1696 */
1697 seen = PySet_New(NULL);
1698 if (seen == NULL)
1699 PyErr_Clear();
1700 print_exception_recursive(f, value, seen);
1701 Py_XDECREF(seen);
1702 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001703}
1704
Guido van Rossum82598051997-03-05 00:20:32 +00001705PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001706PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 PyObject *ret = NULL;
1710 mod_ty mod;
1711 PyArena *arena = PyArena_New();
1712 if (arena == NULL)
1713 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1716 if (mod != NULL)
1717 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1718 PyArena_Free(arena);
1719 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001720}
1721
1722PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001723PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 PyObject *ret;
1727 mod_ty mod;
1728 PyArena *arena = PyArena_New();
1729 if (arena == NULL)
1730 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1733 flags, NULL, arena);
1734 if (closeit)
1735 fclose(fp);
1736 if (mod == NULL) {
1737 PyArena_Free(arena);
1738 return NULL;
1739 }
1740 ret = run_mod(mod, filename, globals, locals, flags, arena);
1741 PyArena_Free(arena);
1742 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001743}
1744
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001745static void
1746flush_io(void)
1747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 PyObject *f, *r;
1749 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 /* Save the current exception */
1752 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 f = PySys_GetObject("stderr");
1755 if (f != NULL) {
1756 r = PyObject_CallMethod(f, "flush", "");
1757 if (r)
1758 Py_DECREF(r);
1759 else
1760 PyErr_Clear();
1761 }
1762 f = PySys_GetObject("stdout");
1763 if (f != NULL) {
1764 r = PyObject_CallMethod(f, "flush", "");
1765 if (r)
1766 Py_DECREF(r);
1767 else
1768 PyErr_Clear();
1769 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001772}
1773
Guido van Rossum82598051997-03-05 00:20:32 +00001774static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001775run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 PyCodeObject *co;
1779 PyObject *v;
1780 co = PyAST_Compile(mod, filename, flags, arena);
1781 if (co == NULL)
1782 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001783 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 Py_DECREF(co);
1785 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001786}
1787
Guido van Rossum82598051997-03-05 00:20:32 +00001788static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001789run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 PyCodeObject *co;
1793 PyObject *v;
1794 long magic;
1795 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 magic = PyMarshal_ReadLongFromFile(fp);
1798 if (magic != PyImport_GetMagicNumber()) {
1799 PyErr_SetString(PyExc_RuntimeError,
1800 "Bad magic number in .pyc file");
1801 return NULL;
1802 }
1803 (void) PyMarshal_ReadLongFromFile(fp);
1804 v = PyMarshal_ReadLastObjectFromFile(fp);
1805 fclose(fp);
1806 if (v == NULL || !PyCode_Check(v)) {
1807 Py_XDECREF(v);
1808 PyErr_SetString(PyExc_RuntimeError,
1809 "Bad code object in .pyc file");
1810 return NULL;
1811 }
1812 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001813 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 if (v && flags)
1815 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1816 Py_DECREF(co);
1817 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001818}
1819
Guido van Rossum82598051997-03-05 00:20:32 +00001820PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001821Py_CompileStringExFlags(const char *str, const char *filename, int start,
1822 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 PyCodeObject *co;
1825 mod_ty mod;
1826 PyArena *arena = PyArena_New();
1827 if (arena == NULL)
1828 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1831 if (mod == NULL) {
1832 PyArena_Free(arena);
1833 return NULL;
1834 }
1835 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1836 PyObject *result = PyAST_mod2obj(mod);
1837 PyArena_Free(arena);
1838 return result;
1839 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001840 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 PyArena_Free(arena);
1842 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001843}
1844
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001845/* For use in Py_LIMITED_API */
1846#undef Py_CompileString
1847PyObject *
1848PyCompileString(const char *str, const char *filename, int start)
1849{
1850 return Py_CompileStringFlags(str, filename, start, NULL);
1851}
1852
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001853struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001854Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 struct symtable *st;
1857 mod_ty mod;
1858 PyCompilerFlags flags;
1859 PyArena *arena = PyArena_New();
1860 if (arena == NULL)
1861 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 flags.cf_flags = 0;
1864 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1865 if (mod == NULL) {
1866 PyArena_Free(arena);
1867 return NULL;
1868 }
1869 st = PySymtable_Build(mod, filename, 0);
1870 PyArena_Free(arena);
1871 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001872}
1873
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874/* Preferred access to parser is through AST. */
1875mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001876PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 mod_ty mod;
1880 PyCompilerFlags localflags;
1881 perrdetail err;
1882 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1885 &_PyParser_Grammar, start, &err,
1886 &iflags);
1887 if (flags == NULL) {
1888 localflags.cf_flags = 0;
1889 flags = &localflags;
1890 }
1891 if (n) {
1892 flags->cf_flags |= iflags & PyCF_MASK;
1893 mod = PyAST_FromNode(n, flags, filename, arena);
1894 PyNode_Free(n);
1895 return mod;
1896 }
1897 else {
1898 err_input(&err);
1899 return NULL;
1900 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901}
1902
1903mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001904PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 int start, char *ps1,
1906 char *ps2, PyCompilerFlags *flags, int *errcode,
1907 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 mod_ty mod;
1910 PyCompilerFlags localflags;
1911 perrdetail err;
1912 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1915 &_PyParser_Grammar,
1916 start, ps1, ps2, &err, &iflags);
1917 if (flags == NULL) {
1918 localflags.cf_flags = 0;
1919 flags = &localflags;
1920 }
1921 if (n) {
1922 flags->cf_flags |= iflags & PyCF_MASK;
1923 mod = PyAST_FromNode(n, flags, filename, arena);
1924 PyNode_Free(n);
1925 return mod;
1926 }
1927 else {
1928 err_input(&err);
1929 if (errcode)
1930 *errcode = err.error;
1931 return NULL;
1932 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001933}
1934
Guido van Rossuma110aa61994-08-29 12:50:44 +00001935/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001936
Guido van Rossuma110aa61994-08-29 12:50:44 +00001937node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001938PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 perrdetail err;
1941 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1942 &_PyParser_Grammar,
1943 start, NULL, NULL, &err, flags);
1944 if (n == NULL)
1945 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001948}
1949
Guido van Rossuma110aa61994-08-29 12:50:44 +00001950/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001951
Guido van Rossuma110aa61994-08-29 12:50:44 +00001952node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001953PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 perrdetail err;
1956 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1957 start, &err, flags);
1958 if (n == NULL)
1959 err_input(&err);
1960 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001961}
1962
1963node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001964PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 perrdetail err;
1968 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1969 &_PyParser_Grammar, start, &err, flags);
1970 if (n == NULL)
1971 err_input(&err);
1972 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001973}
1974
1975node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001976PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001979}
1980
Guido van Rossum66ebd912003-04-17 16:02:26 +00001981/* May want to move a more generalized form of this to parsetok.c or
1982 even parser modules. */
1983
1984void
1985PyParser_SetError(perrdetail *err)
1986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001988}
1989
Guido van Rossuma110aa61994-08-29 12:50:44 +00001990/* Set the error appropriate to the given input error code (see errcode.h) */
1991
1992static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001993err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 PyObject *v, *w, *errtype, *errtext;
1996 PyObject *msg_obj = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001997 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 errtype = PyExc_SyntaxError;
2001 switch (err->error) {
2002 case E_ERROR:
2003 return;
2004 case E_SYNTAX:
2005 errtype = PyExc_IndentationError;
2006 if (err->expected == INDENT)
2007 msg = "expected an indented block";
2008 else if (err->token == INDENT)
2009 msg = "unexpected indent";
2010 else if (err->token == DEDENT)
2011 msg = "unexpected unindent";
2012 else {
2013 errtype = PyExc_SyntaxError;
2014 msg = "invalid syntax";
2015 }
2016 break;
2017 case E_TOKEN:
2018 msg = "invalid token";
2019 break;
2020 case E_EOFS:
2021 msg = "EOF while scanning triple-quoted string literal";
2022 break;
2023 case E_EOLS:
2024 msg = "EOL while scanning string literal";
2025 break;
2026 case E_INTR:
2027 if (!PyErr_Occurred())
2028 PyErr_SetNone(PyExc_KeyboardInterrupt);
2029 goto cleanup;
2030 case E_NOMEM:
2031 PyErr_NoMemory();
2032 goto cleanup;
2033 case E_EOF:
2034 msg = "unexpected EOF while parsing";
2035 break;
2036 case E_TABSPACE:
2037 errtype = PyExc_TabError;
2038 msg = "inconsistent use of tabs and spaces in indentation";
2039 break;
2040 case E_OVERFLOW:
2041 msg = "expression too long";
2042 break;
2043 case E_DEDENT:
2044 errtype = PyExc_IndentationError;
2045 msg = "unindent does not match any outer indentation level";
2046 break;
2047 case E_TOODEEP:
2048 errtype = PyExc_IndentationError;
2049 msg = "too many levels of indentation";
2050 break;
2051 case E_DECODE: {
2052 PyObject *type, *value, *tb;
2053 PyErr_Fetch(&type, &value, &tb);
2054 msg = "unknown decode error";
2055 if (value != NULL)
2056 msg_obj = PyObject_Str(value);
2057 Py_XDECREF(type);
2058 Py_XDECREF(value);
2059 Py_XDECREF(tb);
2060 break;
2061 }
2062 case E_LINECONT:
2063 msg = "unexpected character after line continuation character";
2064 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 case E_IDENTIFIER:
2067 msg = "invalid character in identifier";
2068 break;
2069 default:
2070 fprintf(stderr, "error=%d\n", err->error);
2071 msg = "unknown parsing error";
2072 break;
2073 }
2074 /* err->text may not be UTF-8 in case of decoding errors.
2075 Explicitly convert to an object. */
2076 if (!err->text) {
2077 errtext = Py_None;
2078 Py_INCREF(Py_None);
2079 } else {
2080 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2081 "replace");
2082 }
Victor Stinner2f2ed1f2010-10-16 13:42:53 +00002083 if (err->filename != NULL)
2084 filename = PyUnicode_DecodeFSDefault(err->filename);
2085 else {
2086 Py_INCREF(Py_None);
2087 filename = Py_None;
2088 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002089 if (filename != NULL)
2090 v = Py_BuildValue("(NiiN)", filename,
2091 err->lineno, err->offset, errtext);
2092 else
2093 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (v != NULL) {
2095 if (msg_obj)
2096 w = Py_BuildValue("(OO)", msg_obj, v);
2097 else
2098 w = Py_BuildValue("(sO)", msg, v);
2099 } else
2100 w = NULL;
2101 Py_XDECREF(v);
2102 PyErr_SetObject(errtype, w);
2103 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002104cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 Py_XDECREF(msg_obj);
2106 if (err->text != NULL) {
2107 PyObject_FREE(err->text);
2108 err->text = NULL;
2109 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002110}
2111
2112/* Print fatal error message and abort */
2113
2114void
Tim Peters7c321a82002-07-09 02:57:01 +00002115Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 fprintf(stderr, "Fatal Python error: %s\n", msg);
2118 fflush(stderr); /* it helps in Windows debug build */
2119 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002120 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002122#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 {
2124 size_t len = strlen(msg);
2125 WCHAR* buffer;
2126 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 /* Convert the message to wchar_t. This uses a simple one-to-one
2129 conversion, assuming that the this error message actually uses ASCII
2130 only. If this ceases to be true, we will have to convert. */
2131 buffer = alloca( (len+1) * (sizeof *buffer));
2132 for( i=0; i<=len; ++i)
2133 buffer[i] = msg[i];
2134 OutputDebugStringW(L"Fatal Python error: ");
2135 OutputDebugStringW(buffer);
2136 OutputDebugStringW(L"\n");
2137 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002138#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002140#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002141#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002143}
2144
2145/* Clean up and exit */
2146
Guido van Rossuma110aa61994-08-29 12:50:44 +00002147#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002148#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002149#endif
2150
Collin Winter670e6922007-03-21 02:57:17 +00002151static void (*pyexitfunc)(void) = NULL;
2152/* For the atexit module. */
2153void _Py_PyAtExit(void (*func)(void))
2154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002156}
2157
2158static void
2159call_py_exitfuncs(void)
2160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (pyexitfunc == NULL)
2162 return;
Collin Winter670e6922007-03-21 02:57:17 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 (*pyexitfunc)();
2165 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002166}
2167
Antoine Pitrou011bd622009-10-20 21:52:47 +00002168/* Wait until threading._shutdown completes, provided
2169 the threading module was imported in the first place.
2170 The shutdown routine will wait until all non-daemon
2171 "threading" threads have completed. */
2172static void
2173wait_for_thread_shutdown(void)
2174{
2175#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 PyObject *result;
2177 PyThreadState *tstate = PyThreadState_GET();
2178 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2179 "threading");
2180 if (threading == NULL) {
2181 /* threading not imported */
2182 PyErr_Clear();
2183 return;
2184 }
2185 result = PyObject_CallMethod(threading, "_shutdown", "");
2186 if (result == NULL) {
2187 PyErr_WriteUnraisable(threading);
2188 }
2189 else {
2190 Py_DECREF(result);
2191 }
2192 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002193#endif
2194}
2195
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002196#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002197static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002198static int nexitfuncs = 0;
2199
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002200int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 if (nexitfuncs >= NEXITFUNCS)
2203 return -1;
2204 exitfuncs[nexitfuncs++] = func;
2205 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002206}
2207
Guido van Rossumcc283f51997-08-05 02:22:03 +00002208static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002209call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 while (nexitfuncs > 0)
2212 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 fflush(stdout);
2215 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002216}
2217
2218void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002219Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002224}
2225
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002226static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002227initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002228{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002229#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002231#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002232#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002234#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002235#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002237#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002239}
2240
Guido van Rossum7433b121997-02-14 19:45:36 +00002241
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002242/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2243 *
2244 * All of the code in this function must only use async-signal-safe functions,
2245 * listed at `man 7 signal` or
2246 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2247 */
2248void
2249_Py_RestoreSignals(void)
2250{
2251#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002253#endif
2254#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002256#endif
2257#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002259#endif
2260}
2261
2262
Guido van Rossum7433b121997-02-14 19:45:36 +00002263/*
2264 * The file descriptor fd is considered ``interactive'' if either
2265 * a) isatty(fd) is TRUE, or
2266 * b) the -i flag was given, and the filename associated with
2267 * the descriptor is NULL or "<stdin>" or "???".
2268 */
2269int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002270Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 if (isatty((int)fileno(fp)))
2273 return 1;
2274 if (!Py_InteractiveFlag)
2275 return 0;
2276 return (filename == NULL) ||
2277 (strcmp(filename, "<stdin>") == 0) ||
2278 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002279}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002280
2281
Tim Petersd08e3822003-04-17 15:24:21 +00002282#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002283#if defined(WIN32) && defined(_MSC_VER)
2284
2285/* Stack checking for Microsoft C */
2286
2287#include <malloc.h>
2288#include <excpt.h>
2289
Fred Drakee8de31c2000-08-31 05:38:39 +00002290/*
2291 * Return non-zero when we run out of memory on the stack; zero otherwise.
2292 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002293int
Fred Drake399739f2000-08-31 05:52:44 +00002294PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 __try {
2297 /* alloca throws a stack overflow exception if there's
2298 not enough space left on the stack */
2299 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2300 return 0;
2301 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2302 EXCEPTION_EXECUTE_HANDLER :
2303 EXCEPTION_CONTINUE_SEARCH) {
2304 int errcode = _resetstkoflw();
2305 if (errcode == 0)
2306 {
2307 Py_FatalError("Could not reset the stack!");
2308 }
2309 }
2310 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002311}
2312
2313#endif /* WIN32 && _MSC_VER */
2314
2315/* Alternate implementations can be added here... */
2316
2317#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002318
2319
2320/* Wrappers around sigaction() or signal(). */
2321
2322PyOS_sighandler_t
2323PyOS_getsig(int sig)
2324{
2325#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 struct sigaction context;
2327 if (sigaction(sig, NULL, &context) == -1)
2328 return SIG_ERR;
2329 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002330#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002332/* Special signal handling for the secure CRT in Visual Studio 2005 */
2333#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 switch (sig) {
2335 /* Only these signals are valid */
2336 case SIGINT:
2337 case SIGILL:
2338 case SIGFPE:
2339 case SIGSEGV:
2340 case SIGTERM:
2341 case SIGBREAK:
2342 case SIGABRT:
2343 break;
2344 /* Don't call signal() with other values or it will assert */
2345 default:
2346 return SIG_ERR;
2347 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002348#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 handler = signal(sig, SIG_IGN);
2350 if (handler != SIG_ERR)
2351 signal(sig, handler);
2352 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002353#endif
2354}
2355
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002356/*
2357 * All of the code in this function must only use async-signal-safe functions,
2358 * listed at `man 7 signal` or
2359 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2360 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002361PyOS_sighandler_t
2362PyOS_setsig(int sig, PyOS_sighandler_t handler)
2363{
2364#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* Some code in Modules/signalmodule.c depends on sigaction() being
2366 * used here if HAVE_SIGACTION is defined. Fix that if this code
2367 * changes to invalidate that assumption.
2368 */
2369 struct sigaction context, ocontext;
2370 context.sa_handler = handler;
2371 sigemptyset(&context.sa_mask);
2372 context.sa_flags = 0;
2373 if (sigaction(sig, &context, &ocontext) == -1)
2374 return SIG_ERR;
2375 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002376#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 PyOS_sighandler_t oldhandler;
2378 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002379#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002381#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002383#endif
2384}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002385
2386/* Deprecated C API functions still provided for binary compatiblity */
2387
2388#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002389PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002390PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002393}
2394
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002395#undef PyParser_SimpleParseString
2396PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002397PyParser_SimpleParseString(const char *str, int start)
2398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002400}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002401
2402#undef PyRun_AnyFile
2403PyAPI_FUNC(int)
2404PyRun_AnyFile(FILE *fp, const char *name)
2405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002407}
2408
2409#undef PyRun_AnyFileEx
2410PyAPI_FUNC(int)
2411PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002414}
2415
2416#undef PyRun_AnyFileFlags
2417PyAPI_FUNC(int)
2418PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002421}
2422
2423#undef PyRun_File
2424PyAPI_FUNC(PyObject *)
2425PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002428}
2429
2430#undef PyRun_FileEx
2431PyAPI_FUNC(PyObject *)
2432PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002435}
2436
2437#undef PyRun_FileFlags
2438PyAPI_FUNC(PyObject *)
2439PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002443}
2444
2445#undef PyRun_SimpleFile
2446PyAPI_FUNC(int)
2447PyRun_SimpleFile(FILE *f, const char *p)
2448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002450}
2451
2452#undef PyRun_SimpleFileEx
2453PyAPI_FUNC(int)
2454PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002457}
2458
2459
2460#undef PyRun_String
2461PyAPI_FUNC(PyObject *)
2462PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002465}
2466
2467#undef PyRun_SimpleString
2468PyAPI_FUNC(int)
2469PyRun_SimpleString(const char *s)
2470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002472}
2473
2474#undef Py_CompileString
2475PyAPI_FUNC(PyObject *)
2476Py_CompileString(const char *str, const char *p, int s)
2477{
Georg Brandl8334fd92010-12-04 10:26:46 +00002478 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2479}
2480
2481#undef Py_CompileStringFlags
2482PyAPI_FUNC(PyObject *)
2483Py_CompileStringFlags(const char *str, const char *p, int s,
2484 PyCompilerFlags *flags)
2485{
2486 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002487}
2488
2489#undef PyRun_InteractiveOne
2490PyAPI_FUNC(int)
2491PyRun_InteractiveOne(FILE *f, const char *p)
2492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002494}
2495
2496#undef PyRun_InteractiveLoop
2497PyAPI_FUNC(int)
2498PyRun_InteractiveLoop(FILE *f, const char *p)
2499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002501}
2502
2503#ifdef __cplusplus
2504}
2505#endif