blob: 33dd11bc88595ac3ec84a667178d37f25cb2ab2b [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"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Antoine Pitrou011bd622009-10-20 21:52:47 +000021#include "abstract.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000022
Thomas Wouters0e3f5912006-08-11 14:57:12 +000023#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000024#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000026
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000027#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000028#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000029#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000030
Martin v. Löwis73d538b2003-03-05 15:13:47 +000031#ifdef HAVE_LANGINFO_H
32#include <locale.h>
33#include <langinfo.h>
34#endif
35
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000036#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000037#undef BYTE
38#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000039#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000040#endif
41
Neal Norwitz4281cef2006-03-04 19:58:13 +000042#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000044#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045#define PRINT_TOTAL_REFS() fprintf(stderr, \
46 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
47 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000048#endif
49
50#ifdef __cplusplus
51extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000052#endif
53
Martin v. Löwis790465f2008-04-05 20:41:37 +000054extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000055
Guido van Rossum82598051997-03-05 00:20:32 +000056extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000057
Guido van Rossumb73cc041993-11-01 16:28:59 +000058/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000059static void initmain(void);
Victor Stinnerb744ba12010-05-15 12:27:16 +000060static void initfsencoding(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000061static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000062static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000063static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000066static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000068static void err_input(perrdetail *);
69static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000070static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000071static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000072static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000073extern void _PyUnicode_Init(void);
74extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000075extern int _PyLong_Init(void);
76extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000077
Mark Hammond8d98d2c2003-04-19 15:41:53 +000078#ifdef WITH_THREAD
79extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
80extern void _PyGILState_Fini(void);
81#endif /* WITH_THREAD */
82
Guido van Rossum82598051997-03-05 00:20:32 +000083int Py_DebugFlag; /* Needed by parser.c */
84int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000085int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000086int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000087int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000088int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000089int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000090int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000091int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000092int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000094int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000095
Christian Heimes33fe8092008-04-13 13:53:33 +000096/* PyModule_GetWarningsModule is no longer necessary as of 2.6
97since _warnings is builtin. This API should not be used. */
98PyObject *
99PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000102}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000103
Guido van Rossum25ce5661997-08-02 03:10:38 +0000104static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000105
Thomas Wouters7e474022000-07-16 12:04:32 +0000106/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000107
108int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000109Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000112}
113
Guido van Rossum25ce5661997-08-02 03:10:38 +0000114/* Global initializations. Can be undone by Py_Finalize(). Don't
115 call this twice without an intervening Py_Finalize() call. When
116 initializations fail, a fatal error is issued and the function does
117 not return. On return, the first thread and interpreter state have
118 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000119
Guido van Rossum25ce5661997-08-02 03:10:38 +0000120 Locking: you must hold the interpreter lock while calling this.
121 (If the lock has not yet been initialized, that's equivalent to
122 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000123
Guido van Rossum25ce5661997-08-02 03:10:38 +0000124*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000125
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000126static int
127add_flag(int flag, const char *envs)
128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int env = atoi(envs);
130 if (flag < env)
131 flag = env;
132 if (flag < 1)
133 flag = 1;
134 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000135}
136
Christian Heimes5833a2f2008-10-30 21:40:04 +0000137static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000138get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000139{
Victor Stinner94908bb2010-08-18 21:23:25 +0000140 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000141 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000142
Victor Stinner94908bb2010-08-18 21:23:25 +0000143 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 if (!codec)
145 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 name = PyObject_GetAttrString(codec, "name");
148 Py_CLEAR(codec);
149 if (!name)
150 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000151
Victor Stinner94908bb2010-08-18 21:23:25 +0000152 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner386fe712010-05-19 00:34:15 +0000153 if (name == NULL)
154 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000155 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000157 if (name_str == NULL) {
158 PyErr_NoMemory();
159 return NULL;
160 }
161 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000162
163error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000165 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000167}
Victor Stinner94908bb2010-08-18 21:23:25 +0000168
169#if defined(HAVE_LANGINFO_H) && defined(CODESET)
170static char*
171get_codeset(void)
172{
173 char* codeset = nl_langinfo(CODESET);
174 if (!codeset || codeset[0] == '\0') {
175 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
176 return NULL;
177 }
178 return get_codec_name(codeset);
179}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000180#endif
181
Guido van Rossuma027efa1997-05-05 20:56:21 +0000182void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000183Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyInterpreterState *interp;
186 PyThreadState *tstate;
187 PyObject *bimod, *sysmod, *pstderr;
188 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (initialized)
192 return;
193 initialized = 1;
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);
Guido van Rossum826d8972007-10-30 18:34:07 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000290
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000291 /* Initialize _warnings. */
292 _PyWarnings_Init();
293
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000294 _PyTime_Init();
295
Victor Stinnerb744ba12010-05-15 12:27:16 +0000296 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (install_sigs)
299 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 /* Initialize warnings. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 if (PySys_HasWarnOptions()) {
303 PyObject *warnings_module = PyImport_ImportModule("warnings");
304 if (!warnings_module)
305 PyErr_Clear();
306 Py_XDECREF(warnings_module);
307 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 initmain(); /* Module __main__ */
310 if (initstdio() < 0)
311 Py_FatalError(
312 "Py_Initialize: can't initialize sys standard streams");
313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (!Py_NoSiteFlag)
315 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000316}
317
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000318void
319Py_Initialize(void)
320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000322}
323
324
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000325#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000326extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000327#endif
328
Guido van Rossume8432ac2007-07-09 15:04:50 +0000329/* Flush stdout and stderr */
330
Neal Norwitz2bad9702007-08-27 06:19:22 +0000331static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000332flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 PyObject *fout = PySys_GetObject("stdout");
335 PyObject *ferr = PySys_GetObject("stderr");
336 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (fout != NULL && fout != Py_None) {
339 tmp = PyObject_CallMethod(fout, "flush", "");
340 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000341 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 else
343 Py_DECREF(tmp);
344 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000345
Victor Stinner9467b212010-05-14 00:59:09 +0000346 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 tmp = PyObject_CallMethod(ferr, "flush", "");
348 if (tmp == NULL)
349 PyErr_Clear();
350 else
351 Py_DECREF(tmp);
352 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000353}
354
Guido van Rossum25ce5661997-08-02 03:10:38 +0000355/* Undo the effect of Py_Initialize().
356
357 Beware: if multiple interpreter and/or thread states exist, these
358 are not wiped out; only the current thread and interpreter state
359 are deleted. But since everything else is deleted, those other
360 interpreter and thread states should no longer be used.
361
362 (XXX We should do better, e.g. wipe out all interpreters and
363 threads.)
364
365 Locking: as above.
366
367*/
368
369void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000370Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 PyInterpreterState *interp;
373 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (!initialized)
376 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 /* The interpreter is still entirely intact at this point, and the
381 * exit funcs may be relying on that. In particular, if some thread
382 * or exit func is still waiting to do an import, the import machinery
383 * expects Py_IsInitialized() to return true. So don't say the
384 * interpreter is uninitialized until after the exit funcs have run.
385 * Note that Threading.py uses an exit func to do a join on all the
386 * threads created thru it, so this also protects pending imports in
387 * the threads created via Threading.
388 */
389 call_py_exitfuncs();
390 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 /* Flush stdout+stderr */
393 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Get current thread state and interpreter pointer */
396 tstate = PyThreadState_GET();
397 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 /* Disable signal handling */
400 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 /* Clear type lookup cache */
403 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 /* Collect garbage. This may call finalizers; it's nice to call these
406 * before all modules are destroyed.
407 * XXX If a __del__ or weakref callback is triggered here, and tries to
408 * XXX import a module, bad things can happen, because Python no
409 * XXX longer believes it's initialized.
410 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
411 * XXX is easy to provoke that way. I've also seen, e.g.,
412 * XXX Exception exceptions.ImportError: 'No module named sha'
413 * XXX in <function callback at 0x008F5718> ignored
414 * XXX but I'm unclear on exactly how that one happens. In any case,
415 * XXX I haven't seen a real-life report of either of these.
416 */
417 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000418#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 /* With COUNT_ALLOCS, it helps to run GC multiple times:
420 each collection might release some types from the type
421 list, so they become garbage. */
422 while (PyGC_Collect() > 0)
423 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000424#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000425 /* We run this while most interpreter state is still alive, so that
426 debug information can be printed out */
427 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Destroy all modules */
430 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 /* Flush stdout+stderr (again, in case more was printed) */
433 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* Collect final garbage. This disposes of cycles created by
436 * new-style class definitions, for example.
437 * XXX This is disabled because it caused too many problems. If
438 * XXX a __del__ or weakref callback triggers here, Python code has
439 * XXX a hard time running, because even the sys module has been
440 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
441 * XXX One symptom is a sequence of information-free messages
442 * XXX coming from threads (if a __del__ or callback is invoked,
443 * XXX other threads can execute too, and any exception they encounter
444 * XXX triggers a comedy of errors as subsystem after subsystem
445 * XXX fails to find what it *expects* to find in sys to help report
446 * XXX the exception and consequent unexpected failures). I've also
447 * XXX seen segfaults then, after adding print statements to the
448 * XXX Python code getting called.
449 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000450#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000452#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
455 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000458#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000460#endif
461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000463
Tim Peters9cf25ce2003-04-17 15:21:01 +0000464#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* Display all objects still alive -- this can invoke arbitrary
466 * __repr__ overrides, so requires a mostly-intact interpreter.
467 * Alas, a lot of stuff may still be alive now that will be cleaned
468 * up later.
469 */
470 if (Py_GETENV("PYTHONDUMPREFS"))
471 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000472#endif /* Py_TRACE_REFS */
473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* Clear interpreter state */
475 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 /* Now we decref the exception classes. After this point nothing
478 can raise an exception. That's okay, because each Fini() method
479 below has been checked to make sure no exceptions are ever
480 raised.
481 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000486#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000488#endif /* WITH_THREAD */
489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* Delete current thread */
491 PyThreadState_Swap(NULL);
492 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* Sundry finalizers */
495 PyMethod_Fini();
496 PyFrame_Fini();
497 PyCFunction_Fini();
498 PyTuple_Fini();
499 PyList_Fini();
500 PySet_Fini();
501 PyBytes_Fini();
502 PyByteArray_Fini();
503 PyLong_Fini();
504 PyFloat_Fini();
505 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Cleanup Unicode implementation */
508 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000511 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 free((char*)Py_FileSystemDefaultEncoding);
513 Py_FileSystemDefaultEncoding = NULL;
514 }
Christian Heimesc8967002007-11-30 10:18:26 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* XXX Still allocated:
517 - various static ad-hoc pointers to interned strings
518 - int and float free list blocks
519 - whatever various modules and libraries allocate
520 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000523
Tim Peters269b2a62003-04-17 19:52:29 +0000524#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Display addresses (& refcnts) of all objects still alive.
526 * An address can be used to find the repr of the object, printed
527 * above by _Py_PrintReferences.
528 */
529 if (Py_GETENV("PYTHONDUMPREFS"))
530 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000531#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000532#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (Py_GETENV("PYTHONMALLOCSTATS"))
534 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000535#endif
536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538}
539
540/* Create and initialize a new interpreter and thread, and return the
541 new thread. This requires that Py_Initialize() has been called
542 first.
543
544 Unsuccessful initialization yields a NULL pointer. Note that *no*
545 exception information is available even in this case -- the
546 exception information is held in the thread, and there is no
547 thread.
548
549 Locking: as above.
550
551*/
552
553PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000554Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyInterpreterState *interp;
557 PyThreadState *tstate, *save_tstate;
558 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (!initialized)
561 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 interp = PyInterpreterState_New();
564 if (interp == NULL)
565 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 tstate = PyThreadState_New(interp);
568 if (tstate == NULL) {
569 PyInterpreterState_Delete(interp);
570 return NULL;
571 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 interp->modules = PyDict_New();
578 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579
Victor Stinner49d3f252010-10-17 01:24:53 +0000580 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 if (bimod != NULL) {
582 interp->builtins = PyModule_GetDict(bimod);
583 if (interp->builtins == NULL)
584 goto handle_error;
585 Py_INCREF(interp->builtins);
586 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* initialize builtin exceptions */
589 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000590
Victor Stinner49d3f252010-10-17 01:24:53 +0000591 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (bimod != NULL && sysmod != NULL) {
593 PyObject *pstderr;
594 interp->sysdict = PyModule_GetDict(sysmod);
595 if (interp->sysdict == NULL)
596 goto handle_error;
597 Py_INCREF(interp->sysdict);
598 PySys_SetPath(Py_GetPath());
599 PyDict_SetItemString(interp->sysdict, "modules",
600 interp->modules);
601 /* Set up a preliminary stderr printer until we have enough
602 infrastructure for the io module in place. */
603 pstderr = PyFile_NewStdPrinter(fileno(stderr));
604 if (pstderr == NULL)
605 Py_FatalError("Py_Initialize: can't set preliminary stderr");
606 PySys_SetObject("stderr", pstderr);
607 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 _PyImportHooks_Init();
610 if (initstdio() < 0)
611 Py_FatalError(
612 "Py_Initialize: can't initialize sys standard streams");
613 initmain();
614 if (!Py_NoSiteFlag)
615 initsite();
616 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (!PyErr_Occurred())
619 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000620
Thomas Wouters89f507f2006-12-13 04:49:30 +0000621handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 PyErr_Print();
625 PyThreadState_Clear(tstate);
626 PyThreadState_Swap(save_tstate);
627 PyThreadState_Delete(tstate);
628 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631}
632
633/* Delete an interpreter and its last thread. This requires that the
634 given thread state is current, that the thread has no remaining
635 frames, and that it is its interpreter's only remaining thread.
636 It is a fatal error to violate these constraints.
637
638 (Py_Finalize() doesn't have these constraints -- it zaps
639 everything, regardless.)
640
641 Locking: as above.
642
643*/
644
645void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000646Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (tstate != PyThreadState_GET())
651 Py_FatalError("Py_EndInterpreter: thread is not current");
652 if (tstate->frame != NULL)
653 Py_FatalError("Py_EndInterpreter: thread still has a frame");
654 if (tstate != interp->tstate_head || tstate->next != NULL)
655 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyImport_Cleanup();
658 PyInterpreterState_Clear(interp);
659 PyThreadState_Swap(NULL);
660 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000661}
662
Martin v. Löwis790465f2008-04-05 20:41:37 +0000663static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000664
665void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000666Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (pn && *pn)
669 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000670}
671
Martin v. Löwis790465f2008-04-05 20:41:37 +0000672wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000673Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000676}
677
Martin v. Löwis790465f2008-04-05 20:41:37 +0000678static wchar_t *default_home = NULL;
679static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000680
681void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000682Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000685}
686
Martin v. Löwis790465f2008-04-05 20:41:37 +0000687wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000688Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 wchar_t *home = default_home;
691 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
692 char* chome = Py_GETENV("PYTHONHOME");
693 if (chome) {
694 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
695 if (r != (size_t)-1 && r <= PATH_MAX)
696 home = env_home;
697 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 }
700 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000701}
702
Guido van Rossum6135a871995-01-09 17:53:26 +0000703/* Create __main__ module */
704
705static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000706initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyObject *m, *d;
709 m = PyImport_AddModule("__main__");
710 if (m == NULL)
711 Py_FatalError("can't create __main__ module");
712 d = PyModule_GetDict(m);
713 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
714 PyObject *bimod = PyImport_ImportModule("builtins");
715 if (bimod == NULL ||
716 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
717 Py_FatalError("can't add __builtins__ to __main__");
718 Py_DECREF(bimod);
719 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000720}
721
Victor Stinnerb744ba12010-05-15 12:27:16 +0000722static void
723initfsencoding(void)
724{
725 PyObject *codec;
726#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000727 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000728
Victor Stinner7f84ab52010-06-11 00:36:33 +0000729 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000730 /* On Unix, set the file system encoding according to the
731 user's preference, if the CODESET names a well-known
732 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000733 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000734 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000735 if (codeset == NULL)
736 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000737
Victor Stinnere4743092010-10-19 00:05:51 +0000738 Py_FileSystemDefaultEncoding = codeset;
739 Py_HasFileSystemDefaultEncoding = 0;
740 return;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000741 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000742#endif
743
744 /* the encoding is mbcs, utf-8 or ascii */
745 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
746 if (!codec) {
747 /* Such error can only occurs in critical situations: no more
748 * memory, import a module of the standard library failed,
749 * etc. */
750 Py_FatalError("Py_Initialize: unable to load the file system codec");
751 } else {
752 Py_DECREF(codec);
753 }
754}
755
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000756/* Import the site module (not into __main__ though) */
757
758static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000759initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 PyObject *m;
762 m = PyImport_ImportModule("site");
763 if (m == NULL) {
764 PyErr_Print();
765 Py_Finalize();
766 exit(1);
767 }
768 else {
769 Py_DECREF(m);
770 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000771}
772
Antoine Pitrou05608432009-01-09 18:53:14 +0000773static PyObject*
774create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 int fd, int write_mode, char* name,
776 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
779 const char* mode;
780 PyObject *line_buffering;
781 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 /* stdin is always opened in buffered mode, first because it shouldn't
784 make a difference in common use cases, second because TextIOWrapper
785 depends on the presence of a read1() method which only exists on
786 buffered streams.
787 */
788 if (Py_UnbufferedStdioFlag && write_mode)
789 buffering = 0;
790 else
791 buffering = -1;
792 if (write_mode)
793 mode = "wb";
794 else
795 mode = "rb";
796 buf = PyObject_CallMethod(io, "open", "isiOOOi",
797 fd, mode, buffering,
798 Py_None, Py_None, Py_None, 0);
799 if (buf == NULL)
800 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 if (buffering) {
803 raw = PyObject_GetAttrString(buf, "raw");
804 if (raw == NULL)
805 goto error;
806 }
807 else {
808 raw = buf;
809 Py_INCREF(raw);
810 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 text = PyUnicode_FromString(name);
813 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
814 goto error;
815 res = PyObject_CallMethod(raw, "isatty", "");
816 if (res == NULL)
817 goto error;
818 isatty = PyObject_IsTrue(res);
819 Py_DECREF(res);
820 if (isatty == -1)
821 goto error;
822 if (isatty || Py_UnbufferedStdioFlag)
823 line_buffering = Py_True;
824 else
825 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 Py_CLEAR(raw);
828 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
831 buf, encoding, errors,
832 "\n", line_buffering);
833 Py_CLEAR(buf);
834 if (stream == NULL)
835 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (write_mode)
838 mode = "w";
839 else
840 mode = "r";
841 text = PyUnicode_FromString(mode);
842 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
843 goto error;
844 Py_CLEAR(text);
845 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000846
847error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 Py_XDECREF(buf);
849 Py_XDECREF(stream);
850 Py_XDECREF(text);
851 Py_XDECREF(raw);
852 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000853}
854
Georg Brandl1a3284e2007-12-02 09:40:06 +0000855/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000856static int
857initstdio(void)
858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyObject *iomod = NULL, *wrapper;
860 PyObject *bimod = NULL;
861 PyObject *m;
862 PyObject *std = NULL;
863 int status = 0, fd;
864 PyObject * encoding_attr;
865 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 /* Hack to avoid a nasty recursion issue when Python is invoked
868 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
869 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
870 goto error;
871 }
872 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
875 goto error;
876 }
877 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 if (!(bimod = PyImport_ImportModule("builtins"))) {
880 goto error;
881 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 if (!(iomod = PyImport_ImportModule("io"))) {
884 goto error;
885 }
886 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
887 goto error;
888 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 /* Set builtins.open */
891 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
892 goto error;
893 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 encoding = Py_GETENV("PYTHONIOENCODING");
896 errors = NULL;
897 if (encoding) {
898 encoding = strdup(encoding);
899 errors = strchr(encoding, ':');
900 if (errors) {
901 *errors = '\0';
902 errors++;
903 }
904 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 /* Set sys.stdin */
907 fd = fileno(stdin);
908 /* Under some conditions stdin, stdout and stderr may not be connected
909 * and fileno() may point to an invalid file descriptor. For example
910 * GUI apps don't have valid standard streams by default.
911 */
912 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000913#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 std = Py_None;
915 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000916#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000918#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 }
920 else {
921 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
922 if (std == NULL)
923 goto error;
924 } /* if (fd < 0) */
925 PySys_SetObject("__stdin__", std);
926 PySys_SetObject("stdin", std);
927 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Set sys.stdout */
930 fd = fileno(stdout);
931 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000932#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 std = Py_None;
934 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000935#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000937#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 }
939 else {
940 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
941 if (std == NULL)
942 goto error;
943 } /* if (fd < 0) */
944 PySys_SetObject("__stdout__", std);
945 PySys_SetObject("stdout", std);
946 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000947
Guido van Rossum98297ee2007-11-06 21:34:58 +0000948#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* Set sys.stderr, replaces the preliminary stderr */
950 fd = fileno(stderr);
951 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000952#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 std = Py_None;
954 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000955#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000957#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 }
959 else {
960 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
961 if (std == NULL)
962 goto error;
963 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 /* Same as hack above, pre-import stderr's codec to avoid recursion
966 when import.c tries to write to stderr in verbose mode. */
967 encoding_attr = PyObject_GetAttrString(std, "encoding");
968 if (encoding_attr != NULL) {
969 const char * encoding;
970 encoding = _PyUnicode_AsString(encoding_attr);
971 if (encoding != NULL) {
972 _PyCodec_Lookup(encoding);
973 }
974 }
975 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 PySys_SetObject("__stderr__", std);
978 PySys_SetObject("stderr", std);
979 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000980#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000983 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 status = -1;
985 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 if (encoding)
988 free(encoding);
989 Py_XDECREF(bimod);
990 Py_XDECREF(iomod);
991 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000992}
993
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000994/* Parse input from a file and execute it */
995
996int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000997PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 if (filename == NULL)
1001 filename = "???";
1002 if (Py_FdIsInteractive(fp, filename)) {
1003 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1004 if (closeit)
1005 fclose(fp);
1006 return err;
1007 }
1008 else
1009 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001010}
1011
1012int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001013PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 PyObject *v;
1016 int ret;
1017 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 if (flags == NULL) {
1020 flags = &local_flags;
1021 local_flags.cf_flags = 0;
1022 }
1023 v = PySys_GetObject("ps1");
1024 if (v == NULL) {
1025 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1026 Py_XDECREF(v);
1027 }
1028 v = PySys_GetObject("ps2");
1029 if (v == NULL) {
1030 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1031 Py_XDECREF(v);
1032 }
1033 for (;;) {
1034 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1035 PRINT_TOTAL_REFS();
1036 if (ret == E_EOF)
1037 return 0;
1038 /*
1039 if (ret == E_NOMEM)
1040 return -1;
1041 */
1042 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001043}
1044
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001045/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001046static int PARSER_FLAGS(PyCompilerFlags *flags)
1047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 int parser_flags = 0;
1049 if (!flags)
1050 return 0;
1051 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1052 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1053 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1054 parser_flags |= PyPARSE_IGNORE_COOKIE;
1055 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1056 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1057 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001058}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001059
Thomas Wouters89f507f2006-12-13 04:49:30 +00001060#if 0
1061/* Keep an example of flags with future keyword support. */
1062#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1064 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1065 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1066 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001067#endif
1068
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001069int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001070PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 PyObject *m, *d, *v, *w, *oenc = NULL;
1073 mod_ty mod;
1074 PyArena *arena;
1075 char *ps1 = "", *ps2 = "", *enc = NULL;
1076 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 if (fp == stdin) {
1079 /* Fetch encoding from sys.stdin */
1080 v = PySys_GetObject("stdin");
1081 if (v == NULL || v == Py_None)
1082 return -1;
1083 oenc = PyObject_GetAttrString(v, "encoding");
1084 if (!oenc)
1085 return -1;
1086 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001087 if (enc == NULL)
1088 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 }
1090 v = PySys_GetObject("ps1");
1091 if (v != NULL) {
1092 v = PyObject_Str(v);
1093 if (v == NULL)
1094 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001095 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001097 if (ps1 == NULL) {
1098 PyErr_Clear();
1099 ps1 = "";
1100 }
1101 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 }
1103 w = PySys_GetObject("ps2");
1104 if (w != NULL) {
1105 w = PyObject_Str(w);
1106 if (w == NULL)
1107 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001108 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001110 if (ps2 == NULL) {
1111 PyErr_Clear();
1112 ps2 = "";
1113 }
1114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 }
1116 arena = PyArena_New();
1117 if (arena == NULL) {
1118 Py_XDECREF(v);
1119 Py_XDECREF(w);
1120 Py_XDECREF(oenc);
1121 return -1;
1122 }
1123 mod = PyParser_ASTFromFile(fp, filename, enc,
1124 Py_single_input, ps1, ps2,
1125 flags, &errcode, arena);
1126 Py_XDECREF(v);
1127 Py_XDECREF(w);
1128 Py_XDECREF(oenc);
1129 if (mod == NULL) {
1130 PyArena_Free(arena);
1131 if (errcode == E_EOF) {
1132 PyErr_Clear();
1133 return E_EOF;
1134 }
1135 PyErr_Print();
1136 return -1;
1137 }
1138 m = PyImport_AddModule("__main__");
1139 if (m == NULL) {
1140 PyArena_Free(arena);
1141 return -1;
1142 }
1143 d = PyModule_GetDict(m);
1144 v = run_mod(mod, filename, d, d, flags, arena);
1145 PyArena_Free(arena);
1146 flush_io();
1147 if (v == NULL) {
1148 PyErr_Print();
1149 return -1;
1150 }
1151 Py_DECREF(v);
1152 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001153}
1154
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001155/* Check whether a file maybe a pyc file: Look at the extension,
1156 the file type, and, if we may close it, at the first few bytes. */
1157
1158static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001159maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1162 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 /* Only look into the file if we are allowed to close it, since
1165 it then should also be seekable. */
1166 if (closeit) {
1167 /* Read only two bytes of the magic. If the file was opened in
1168 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1169 be read as they are on disk. */
1170 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1171 unsigned char buf[2];
1172 /* Mess: In case of -x, the stream is NOT at its start now,
1173 and ungetc() was used to push back the first newline,
1174 which makes the current stream position formally undefined,
1175 and a x-platform nightmare.
1176 Unfortunately, we have no direct way to know whether -x
1177 was specified. So we use a terrible hack: if the current
1178 stream position is not 0, we assume -x was specified, and
1179 give up. Bug 132850 on SourceForge spells out the
1180 hopelessness of trying anything else (fseek and ftell
1181 don't work predictably x-platform for text-mode files).
1182 */
1183 int ispyc = 0;
1184 if (ftell(fp) == 0) {
1185 if (fread(buf, 1, 2, fp) == 2 &&
1186 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1187 ispyc = 1;
1188 rewind(fp);
1189 }
1190 return ispyc;
1191 }
1192 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001193}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001194
Guido van Rossum0df002c2000-08-27 19:21:52 +00001195int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001196PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyObject *m, *d, *v;
1200 const char *ext;
1201 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 m = PyImport_AddModule("__main__");
1204 if (m == NULL)
1205 return -1;
1206 d = PyModule_GetDict(m);
1207 if (PyDict_GetItemString(d, "__file__") == NULL) {
1208 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001209 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 if (f == NULL)
1211 return -1;
1212 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1213 Py_DECREF(f);
1214 return -1;
1215 }
1216 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1217 return -1;
1218 set_file_name = 1;
1219 Py_DECREF(f);
1220 }
1221 len = strlen(filename);
1222 ext = filename + len - (len > 4 ? 4 : 0);
1223 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1224 /* Try to run a pyc file. First, re-open in binary */
1225 if (closeit)
1226 fclose(fp);
1227 if ((fp = fopen(filename, "rb")) == NULL) {
1228 fprintf(stderr, "python: Can't reopen .pyc file\n");
1229 ret = -1;
1230 goto done;
1231 }
1232 /* Turn on optimization if a .pyo file is given */
1233 if (strcmp(ext, ".pyo") == 0)
1234 Py_OptimizeFlag = 1;
1235 v = run_pyc_file(fp, filename, d, d, flags);
1236 } else {
1237 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1238 closeit, flags);
1239 }
1240 flush_io();
1241 if (v == NULL) {
1242 PyErr_Print();
1243 ret = -1;
1244 goto done;
1245 }
1246 Py_DECREF(v);
1247 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001248 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1250 PyErr_Clear();
1251 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001252}
1253
1254int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001255PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 PyObject *m, *d, *v;
1258 m = PyImport_AddModule("__main__");
1259 if (m == NULL)
1260 return -1;
1261 d = PyModule_GetDict(m);
1262 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1263 if (v == NULL) {
1264 PyErr_Print();
1265 return -1;
1266 }
1267 Py_DECREF(v);
1268 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001269}
1270
Barry Warsaw035574d1997-08-29 22:07:17 +00001271static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001272parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 long hold;
1276 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 /* old style errors */
1279 if (PyTuple_Check(err))
1280 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1281 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (! (v = PyObject_GetAttrString(err, "msg")))
1286 goto finally;
1287 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (!(v = PyObject_GetAttrString(err, "filename")))
1290 goto finally;
1291 if (v == Py_None)
1292 *filename = NULL;
1293 else if (! (*filename = _PyUnicode_AsString(v)))
1294 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 Py_DECREF(v);
1297 if (!(v = PyObject_GetAttrString(err, "lineno")))
1298 goto finally;
1299 hold = PyLong_AsLong(v);
1300 Py_DECREF(v);
1301 v = NULL;
1302 if (hold < 0 && PyErr_Occurred())
1303 goto finally;
1304 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 if (!(v = PyObject_GetAttrString(err, "offset")))
1307 goto finally;
1308 if (v == Py_None) {
1309 *offset = -1;
1310 Py_DECREF(v);
1311 v = NULL;
1312 } else {
1313 hold = PyLong_AsLong(v);
1314 Py_DECREF(v);
1315 v = NULL;
1316 if (hold < 0 && PyErr_Occurred())
1317 goto finally;
1318 *offset = (int)hold;
1319 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 if (!(v = PyObject_GetAttrString(err, "text")))
1322 goto finally;
1323 if (v == Py_None)
1324 *text = NULL;
1325 else if (!PyUnicode_Check(v) ||
1326 !(*text = _PyUnicode_AsString(v)))
1327 goto finally;
1328 Py_DECREF(v);
1329 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001330
1331finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 Py_XDECREF(v);
1333 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001334}
1335
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001336void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001337PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001340}
1341
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001342static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001343print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 char *nl;
1346 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001347 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1348 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 for (;;) {
1350 nl = strchr(text, '\n');
1351 if (nl == NULL || nl-text >= offset)
1352 break;
1353 offset -= (int)(nl+1-text);
1354 text = nl+1;
1355 }
1356 while (*text == ' ' || *text == '\t') {
1357 text++;
1358 offset--;
1359 }
1360 }
1361 PyFile_WriteString(" ", f);
1362 PyFile_WriteString(text, f);
1363 if (*text == '\0' || text[strlen(text)-1] != '\n')
1364 PyFile_WriteString("\n", f);
1365 if (offset == -1)
1366 return;
1367 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001368 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001371}
1372
Guido van Rossum66e8e862001-03-23 17:54:43 +00001373static void
1374handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyObject *exception, *value, *tb;
1377 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (Py_InspectFlag)
1380 /* Don't exit if -i flag was given. This flag is set to 0
1381 * when entering interactive mode for inspecting. */
1382 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 PyErr_Fetch(&exception, &value, &tb);
1385 fflush(stdout);
1386 if (value == NULL || value == Py_None)
1387 goto done;
1388 if (PyExceptionInstance_Check(value)) {
1389 /* The error code should be in the `code' attribute. */
1390 PyObject *code = PyObject_GetAttrString(value, "code");
1391 if (code) {
1392 Py_DECREF(value);
1393 value = code;
1394 if (value == Py_None)
1395 goto done;
1396 }
1397 /* If we failed to dig out the 'code' attribute,
1398 just let the else clause below print the error. */
1399 }
1400 if (PyLong_Check(value))
1401 exitcode = (int)PyLong_AsLong(value);
1402 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001403 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001404 if (sys_stderr != NULL && sys_stderr != Py_None) {
1405 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1406 } else {
1407 PyObject_Print(value, stderr, Py_PRINT_RAW);
1408 fflush(stderr);
1409 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PySys_WriteStderr("\n");
1411 exitcode = 1;
1412 }
Tim Peterscf615b52003-04-19 18:47:02 +00001413 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 /* Restore and clear the exception info, in order to properly decref
1415 * the exception, value, and traceback. If we just exit instead,
1416 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1417 * some finalizers from running.
1418 */
1419 PyErr_Restore(exception, value, tb);
1420 PyErr_Clear();
1421 Py_Exit(exitcode);
1422 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001423}
1424
1425void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001426PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1431 handle_system_exit();
1432 }
1433 PyErr_Fetch(&exception, &v, &tb);
1434 if (exception == NULL)
1435 return;
1436 PyErr_NormalizeException(&exception, &v, &tb);
1437 if (tb == NULL) {
1438 tb = Py_None;
1439 Py_INCREF(tb);
1440 }
1441 PyException_SetTraceback(v, tb);
1442 if (exception == NULL)
1443 return;
1444 /* Now we know v != NULL too */
1445 if (set_sys_last_vars) {
1446 PySys_SetObject("last_type", exception);
1447 PySys_SetObject("last_value", v);
1448 PySys_SetObject("last_traceback", tb);
1449 }
1450 hook = PySys_GetObject("excepthook");
1451 if (hook) {
1452 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1453 PyObject *result = PyEval_CallObject(hook, args);
1454 if (result == NULL) {
1455 PyObject *exception2, *v2, *tb2;
1456 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1457 handle_system_exit();
1458 }
1459 PyErr_Fetch(&exception2, &v2, &tb2);
1460 PyErr_NormalizeException(&exception2, &v2, &tb2);
1461 /* It should not be possible for exception2 or v2
1462 to be NULL. However PyErr_Display() can't
1463 tolerate NULLs, so just be safe. */
1464 if (exception2 == NULL) {
1465 exception2 = Py_None;
1466 Py_INCREF(exception2);
1467 }
1468 if (v2 == NULL) {
1469 v2 = Py_None;
1470 Py_INCREF(v2);
1471 }
1472 fflush(stdout);
1473 PySys_WriteStderr("Error in sys.excepthook:\n");
1474 PyErr_Display(exception2, v2, tb2);
1475 PySys_WriteStderr("\nOriginal exception was:\n");
1476 PyErr_Display(exception, v, tb);
1477 Py_DECREF(exception2);
1478 Py_DECREF(v2);
1479 Py_XDECREF(tb2);
1480 }
1481 Py_XDECREF(result);
1482 Py_XDECREF(args);
1483 } else {
1484 PySys_WriteStderr("sys.excepthook is missing\n");
1485 PyErr_Display(exception, v, tb);
1486 }
1487 Py_XDECREF(exception);
1488 Py_XDECREF(v);
1489 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001490}
1491
Benjamin Petersone6528212008-07-15 15:32:09 +00001492static void
1493print_exception(PyObject *f, PyObject *value)
1494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 int err = 0;
1496 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 if (!PyExceptionInstance_Check(value)) {
1499 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1500 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1501 PyFile_WriteString(" found\n", f);
1502 return;
1503 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 Py_INCREF(value);
1506 fflush(stdout);
1507 type = (PyObject *) Py_TYPE(value);
1508 tb = PyException_GetTraceback(value);
1509 if (tb && tb != Py_None)
1510 err = PyTraceBack_Print(tb, f);
1511 if (err == 0 &&
1512 PyObject_HasAttrString(value, "print_file_and_line"))
1513 {
1514 PyObject *message;
1515 const char *filename, *text;
1516 int lineno, offset;
1517 if (!parse_syntax_error(value, &message, &filename,
1518 &lineno, &offset, &text))
1519 PyErr_Clear();
1520 else {
1521 char buf[10];
1522 PyFile_WriteString(" File \"", f);
1523 if (filename == NULL)
1524 PyFile_WriteString("<string>", f);
1525 else
1526 PyFile_WriteString(filename, f);
1527 PyFile_WriteString("\", line ", f);
1528 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1529 PyFile_WriteString(buf, f);
1530 PyFile_WriteString("\n", f);
1531 if (text != NULL)
1532 print_error_text(f, offset, text);
1533 Py_DECREF(value);
1534 value = message;
1535 /* Can't be bothered to check all those
1536 PyFile_WriteString() calls */
1537 if (PyErr_Occurred())
1538 err = -1;
1539 }
1540 }
1541 if (err) {
1542 /* Don't do anything else */
1543 }
1544 else {
1545 PyObject* moduleName;
1546 char* className;
1547 assert(PyExceptionClass_Check(type));
1548 className = PyExceptionClass_Name(type);
1549 if (className != NULL) {
1550 char *dot = strrchr(className, '.');
1551 if (dot != NULL)
1552 className = dot+1;
1553 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 moduleName = PyObject_GetAttrString(type, "__module__");
1556 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1557 {
1558 Py_DECREF(moduleName);
1559 err = PyFile_WriteString("<unknown>", f);
1560 }
1561 else {
1562 char* modstr = _PyUnicode_AsString(moduleName);
1563 if (modstr && strcmp(modstr, "builtins"))
1564 {
1565 err = PyFile_WriteString(modstr, f);
1566 err += PyFile_WriteString(".", f);
1567 }
1568 Py_DECREF(moduleName);
1569 }
1570 if (err == 0) {
1571 if (className == NULL)
1572 err = PyFile_WriteString("<unknown>", f);
1573 else
1574 err = PyFile_WriteString(className, f);
1575 }
1576 }
1577 if (err == 0 && (value != Py_None)) {
1578 PyObject *s = PyObject_Str(value);
1579 /* only print colon if the str() of the
1580 object is not the empty string
1581 */
1582 if (s == NULL)
1583 err = -1;
1584 else if (!PyUnicode_Check(s) ||
1585 PyUnicode_GetSize(s) != 0)
1586 err = PyFile_WriteString(": ", f);
1587 if (err == 0)
1588 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1589 Py_XDECREF(s);
1590 }
1591 /* try to write a newline in any case */
1592 err += PyFile_WriteString("\n", f);
1593 Py_XDECREF(tb);
1594 Py_DECREF(value);
1595 /* If an error happened here, don't show it.
1596 XXX This is wrong, but too many callers rely on this behavior. */
1597 if (err != 0)
1598 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001599}
1600
1601static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 "\nThe above exception was the direct cause "
1603 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001604
1605static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 "\nDuring handling of the above exception, "
1607 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001608
1609static void
1610print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 int err = 0, res;
1613 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 if (seen != NULL) {
1616 /* Exception chaining */
1617 if (PySet_Add(seen, value) == -1)
1618 PyErr_Clear();
1619 else if (PyExceptionInstance_Check(value)) {
1620 cause = PyException_GetCause(value);
1621 context = PyException_GetContext(value);
1622 if (cause) {
1623 res = PySet_Contains(seen, cause);
1624 if (res == -1)
1625 PyErr_Clear();
1626 if (res == 0) {
1627 print_exception_recursive(
1628 f, cause, seen);
1629 err |= PyFile_WriteString(
1630 cause_message, f);
1631 }
1632 }
1633 else if (context) {
1634 res = PySet_Contains(seen, context);
1635 if (res == -1)
1636 PyErr_Clear();
1637 if (res == 0) {
1638 print_exception_recursive(
1639 f, context, seen);
1640 err |= PyFile_WriteString(
1641 context_message, f);
1642 }
1643 }
1644 Py_XDECREF(context);
1645 Py_XDECREF(cause);
1646 }
1647 }
1648 print_exception(f, value);
1649 if (err != 0)
1650 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001651}
1652
Thomas Wouters477c8d52006-05-27 19:21:47 +00001653void
1654PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 PyObject *seen;
1657 PyObject *f = PySys_GetObject("stderr");
1658 if (f == Py_None) {
1659 /* pass */
1660 }
1661 else if (f == NULL) {
1662 _PyObject_Dump(value);
1663 fprintf(stderr, "lost sys.stderr\n");
1664 }
1665 else {
1666 /* We choose to ignore seen being possibly NULL, and report
1667 at least the main exception (it could be a MemoryError).
1668 */
1669 seen = PySet_New(NULL);
1670 if (seen == NULL)
1671 PyErr_Clear();
1672 print_exception_recursive(f, value, seen);
1673 Py_XDECREF(seen);
1674 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001675}
1676
Guido van Rossum82598051997-03-05 00:20:32 +00001677PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001678PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 PyObject *ret = NULL;
1682 mod_ty mod;
1683 PyArena *arena = PyArena_New();
1684 if (arena == NULL)
1685 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1688 if (mod != NULL)
1689 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1690 PyArena_Free(arena);
1691 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001692}
1693
1694PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001695PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 PyObject *ret;
1699 mod_ty mod;
1700 PyArena *arena = PyArena_New();
1701 if (arena == NULL)
1702 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1705 flags, NULL, arena);
1706 if (closeit)
1707 fclose(fp);
1708 if (mod == NULL) {
1709 PyArena_Free(arena);
1710 return NULL;
1711 }
1712 ret = run_mod(mod, filename, globals, locals, flags, arena);
1713 PyArena_Free(arena);
1714 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001715}
1716
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001717static void
1718flush_io(void)
1719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 PyObject *f, *r;
1721 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 /* Save the current exception */
1724 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 f = PySys_GetObject("stderr");
1727 if (f != NULL) {
1728 r = PyObject_CallMethod(f, "flush", "");
1729 if (r)
1730 Py_DECREF(r);
1731 else
1732 PyErr_Clear();
1733 }
1734 f = PySys_GetObject("stdout");
1735 if (f != NULL) {
1736 r = PyObject_CallMethod(f, "flush", "");
1737 if (r)
1738 Py_DECREF(r);
1739 else
1740 PyErr_Clear();
1741 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001744}
1745
Guido van Rossum82598051997-03-05 00:20:32 +00001746static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001747run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 PyCodeObject *co;
1751 PyObject *v;
1752 co = PyAST_Compile(mod, filename, flags, arena);
1753 if (co == NULL)
1754 return NULL;
1755 v = PyEval_EvalCode(co, globals, locals);
1756 Py_DECREF(co);
1757 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001758}
1759
Guido van Rossum82598051997-03-05 00:20:32 +00001760static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001761run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 PyCodeObject *co;
1765 PyObject *v;
1766 long magic;
1767 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 magic = PyMarshal_ReadLongFromFile(fp);
1770 if (magic != PyImport_GetMagicNumber()) {
1771 PyErr_SetString(PyExc_RuntimeError,
1772 "Bad magic number in .pyc file");
1773 return NULL;
1774 }
1775 (void) PyMarshal_ReadLongFromFile(fp);
1776 v = PyMarshal_ReadLastObjectFromFile(fp);
1777 fclose(fp);
1778 if (v == NULL || !PyCode_Check(v)) {
1779 Py_XDECREF(v);
1780 PyErr_SetString(PyExc_RuntimeError,
1781 "Bad code object in .pyc file");
1782 return NULL;
1783 }
1784 co = (PyCodeObject *)v;
1785 v = PyEval_EvalCode(co, globals, locals);
1786 if (v && flags)
1787 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1788 Py_DECREF(co);
1789 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001790}
1791
Guido van Rossum82598051997-03-05 00:20:32 +00001792PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001793Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 PyCodeObject *co;
1797 mod_ty mod;
1798 PyArena *arena = PyArena_New();
1799 if (arena == NULL)
1800 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1803 if (mod == NULL) {
1804 PyArena_Free(arena);
1805 return NULL;
1806 }
1807 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1808 PyObject *result = PyAST_mod2obj(mod);
1809 PyArena_Free(arena);
1810 return result;
1811 }
1812 co = PyAST_Compile(mod, filename, flags, arena);
1813 PyArena_Free(arena);
1814 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001815}
1816
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001817struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001818Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 struct symtable *st;
1821 mod_ty mod;
1822 PyCompilerFlags flags;
1823 PyArena *arena = PyArena_New();
1824 if (arena == NULL)
1825 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 flags.cf_flags = 0;
1828 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1829 if (mod == NULL) {
1830 PyArena_Free(arena);
1831 return NULL;
1832 }
1833 st = PySymtable_Build(mod, filename, 0);
1834 PyArena_Free(arena);
1835 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001836}
1837
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001838/* Preferred access to parser is through AST. */
1839mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001840PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 mod_ty mod;
1844 PyCompilerFlags localflags;
1845 perrdetail err;
1846 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1849 &_PyParser_Grammar, start, &err,
1850 &iflags);
1851 if (flags == NULL) {
1852 localflags.cf_flags = 0;
1853 flags = &localflags;
1854 }
1855 if (n) {
1856 flags->cf_flags |= iflags & PyCF_MASK;
1857 mod = PyAST_FromNode(n, flags, filename, arena);
1858 PyNode_Free(n);
1859 return mod;
1860 }
1861 else {
1862 err_input(&err);
1863 return NULL;
1864 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001865}
1866
1867mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001868PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 int start, char *ps1,
1870 char *ps2, PyCompilerFlags *flags, int *errcode,
1871 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 mod_ty mod;
1874 PyCompilerFlags localflags;
1875 perrdetail err;
1876 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1879 &_PyParser_Grammar,
1880 start, ps1, ps2, &err, &iflags);
1881 if (flags == NULL) {
1882 localflags.cf_flags = 0;
1883 flags = &localflags;
1884 }
1885 if (n) {
1886 flags->cf_flags |= iflags & PyCF_MASK;
1887 mod = PyAST_FromNode(n, flags, filename, arena);
1888 PyNode_Free(n);
1889 return mod;
1890 }
1891 else {
1892 err_input(&err);
1893 if (errcode)
1894 *errcode = err.error;
1895 return NULL;
1896 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001897}
1898
Guido van Rossuma110aa61994-08-29 12:50:44 +00001899/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001900
Guido van Rossuma110aa61994-08-29 12:50:44 +00001901node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001902PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 perrdetail err;
1905 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1906 &_PyParser_Grammar,
1907 start, NULL, NULL, &err, flags);
1908 if (n == NULL)
1909 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001912}
1913
Guido van Rossuma110aa61994-08-29 12:50:44 +00001914/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001915
Guido van Rossuma110aa61994-08-29 12:50:44 +00001916node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001917PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 perrdetail err;
1920 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1921 start, &err, flags);
1922 if (n == NULL)
1923 err_input(&err);
1924 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001925}
1926
1927node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001928PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 perrdetail err;
1932 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1933 &_PyParser_Grammar, start, &err, flags);
1934 if (n == NULL)
1935 err_input(&err);
1936 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001937}
1938
1939node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001940PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001943}
1944
Guido van Rossum66ebd912003-04-17 16:02:26 +00001945/* May want to move a more generalized form of this to parsetok.c or
1946 even parser modules. */
1947
1948void
1949PyParser_SetError(perrdetail *err)
1950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001952}
1953
Guido van Rossuma110aa61994-08-29 12:50:44 +00001954/* Set the error appropriate to the given input error code (see errcode.h) */
1955
1956static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001957err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 PyObject *v, *w, *errtype, *errtext;
1960 PyObject *msg_obj = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001961 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 errtype = PyExc_SyntaxError;
1965 switch (err->error) {
1966 case E_ERROR:
1967 return;
1968 case E_SYNTAX:
1969 errtype = PyExc_IndentationError;
1970 if (err->expected == INDENT)
1971 msg = "expected an indented block";
1972 else if (err->token == INDENT)
1973 msg = "unexpected indent";
1974 else if (err->token == DEDENT)
1975 msg = "unexpected unindent";
1976 else {
1977 errtype = PyExc_SyntaxError;
1978 msg = "invalid syntax";
1979 }
1980 break;
1981 case E_TOKEN:
1982 msg = "invalid token";
1983 break;
1984 case E_EOFS:
1985 msg = "EOF while scanning triple-quoted string literal";
1986 break;
1987 case E_EOLS:
1988 msg = "EOL while scanning string literal";
1989 break;
1990 case E_INTR:
1991 if (!PyErr_Occurred())
1992 PyErr_SetNone(PyExc_KeyboardInterrupt);
1993 goto cleanup;
1994 case E_NOMEM:
1995 PyErr_NoMemory();
1996 goto cleanup;
1997 case E_EOF:
1998 msg = "unexpected EOF while parsing";
1999 break;
2000 case E_TABSPACE:
2001 errtype = PyExc_TabError;
2002 msg = "inconsistent use of tabs and spaces in indentation";
2003 break;
2004 case E_OVERFLOW:
2005 msg = "expression too long";
2006 break;
2007 case E_DEDENT:
2008 errtype = PyExc_IndentationError;
2009 msg = "unindent does not match any outer indentation level";
2010 break;
2011 case E_TOODEEP:
2012 errtype = PyExc_IndentationError;
2013 msg = "too many levels of indentation";
2014 break;
2015 case E_DECODE: {
2016 PyObject *type, *value, *tb;
2017 PyErr_Fetch(&type, &value, &tb);
2018 msg = "unknown decode error";
2019 if (value != NULL)
2020 msg_obj = PyObject_Str(value);
2021 Py_XDECREF(type);
2022 Py_XDECREF(value);
2023 Py_XDECREF(tb);
2024 break;
2025 }
2026 case E_LINECONT:
2027 msg = "unexpected character after line continuation character";
2028 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 case E_IDENTIFIER:
2031 msg = "invalid character in identifier";
2032 break;
2033 default:
2034 fprintf(stderr, "error=%d\n", err->error);
2035 msg = "unknown parsing error";
2036 break;
2037 }
2038 /* err->text may not be UTF-8 in case of decoding errors.
2039 Explicitly convert to an object. */
2040 if (!err->text) {
2041 errtext = Py_None;
2042 Py_INCREF(Py_None);
2043 } else {
2044 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2045 "replace");
2046 }
Victor Stinner2f2ed1f2010-10-16 13:42:53 +00002047 if (err->filename != NULL)
2048 filename = PyUnicode_DecodeFSDefault(err->filename);
2049 else {
2050 Py_INCREF(Py_None);
2051 filename = Py_None;
2052 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002053 if (filename != NULL)
2054 v = Py_BuildValue("(NiiN)", filename,
2055 err->lineno, err->offset, errtext);
2056 else
2057 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if (v != NULL) {
2059 if (msg_obj)
2060 w = Py_BuildValue("(OO)", msg_obj, v);
2061 else
2062 w = Py_BuildValue("(sO)", msg, v);
2063 } else
2064 w = NULL;
2065 Py_XDECREF(v);
2066 PyErr_SetObject(errtype, w);
2067 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002068cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 Py_XDECREF(msg_obj);
2070 if (err->text != NULL) {
2071 PyObject_FREE(err->text);
2072 err->text = NULL;
2073 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002074}
2075
2076/* Print fatal error message and abort */
2077
2078void
Tim Peters7c321a82002-07-09 02:57:01 +00002079Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 fprintf(stderr, "Fatal Python error: %s\n", msg);
2082 fflush(stderr); /* it helps in Windows debug build */
2083 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002084 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002086#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 {
2088 size_t len = strlen(msg);
2089 WCHAR* buffer;
2090 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 /* Convert the message to wchar_t. This uses a simple one-to-one
2093 conversion, assuming that the this error message actually uses ASCII
2094 only. If this ceases to be true, we will have to convert. */
2095 buffer = alloca( (len+1) * (sizeof *buffer));
2096 for( i=0; i<=len; ++i)
2097 buffer[i] = msg[i];
2098 OutputDebugStringW(L"Fatal Python error: ");
2099 OutputDebugStringW(buffer);
2100 OutputDebugStringW(L"\n");
2101 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002102#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002104#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002105#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002107}
2108
2109/* Clean up and exit */
2110
Guido van Rossuma110aa61994-08-29 12:50:44 +00002111#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002112#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002113#endif
2114
Collin Winter670e6922007-03-21 02:57:17 +00002115static void (*pyexitfunc)(void) = NULL;
2116/* For the atexit module. */
2117void _Py_PyAtExit(void (*func)(void))
2118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002120}
2121
2122static void
2123call_py_exitfuncs(void)
2124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 if (pyexitfunc == NULL)
2126 return;
Collin Winter670e6922007-03-21 02:57:17 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 (*pyexitfunc)();
2129 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002130}
2131
Antoine Pitrou011bd622009-10-20 21:52:47 +00002132/* Wait until threading._shutdown completes, provided
2133 the threading module was imported in the first place.
2134 The shutdown routine will wait until all non-daemon
2135 "threading" threads have completed. */
2136static void
2137wait_for_thread_shutdown(void)
2138{
2139#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 PyObject *result;
2141 PyThreadState *tstate = PyThreadState_GET();
2142 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2143 "threading");
2144 if (threading == NULL) {
2145 /* threading not imported */
2146 PyErr_Clear();
2147 return;
2148 }
2149 result = PyObject_CallMethod(threading, "_shutdown", "");
2150 if (result == NULL) {
2151 PyErr_WriteUnraisable(threading);
2152 }
2153 else {
2154 Py_DECREF(result);
2155 }
2156 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002157#endif
2158}
2159
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002160#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002161static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002162static int nexitfuncs = 0;
2163
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002164int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (nexitfuncs >= NEXITFUNCS)
2167 return -1;
2168 exitfuncs[nexitfuncs++] = func;
2169 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002170}
2171
Guido van Rossumcc283f51997-08-05 02:22:03 +00002172static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002173call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 while (nexitfuncs > 0)
2176 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 fflush(stdout);
2179 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002180}
2181
2182void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002183Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002188}
2189
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002190static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002191initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002192{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002193#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002195#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002196#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002198#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002199#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002201#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002203}
2204
Guido van Rossum7433b121997-02-14 19:45:36 +00002205
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002206/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2207 *
2208 * All of the code in this function must only use async-signal-safe functions,
2209 * listed at `man 7 signal` or
2210 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2211 */
2212void
2213_Py_RestoreSignals(void)
2214{
2215#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002217#endif
2218#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002220#endif
2221#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002223#endif
2224}
2225
2226
Guido van Rossum7433b121997-02-14 19:45:36 +00002227/*
2228 * The file descriptor fd is considered ``interactive'' if either
2229 * a) isatty(fd) is TRUE, or
2230 * b) the -i flag was given, and the filename associated with
2231 * the descriptor is NULL or "<stdin>" or "???".
2232 */
2233int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002234Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 if (isatty((int)fileno(fp)))
2237 return 1;
2238 if (!Py_InteractiveFlag)
2239 return 0;
2240 return (filename == NULL) ||
2241 (strcmp(filename, "<stdin>") == 0) ||
2242 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002243}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002244
2245
Tim Petersd08e3822003-04-17 15:24:21 +00002246#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002247#if defined(WIN32) && defined(_MSC_VER)
2248
2249/* Stack checking for Microsoft C */
2250
2251#include <malloc.h>
2252#include <excpt.h>
2253
Fred Drakee8de31c2000-08-31 05:38:39 +00002254/*
2255 * Return non-zero when we run out of memory on the stack; zero otherwise.
2256 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002257int
Fred Drake399739f2000-08-31 05:52:44 +00002258PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 __try {
2261 /* alloca throws a stack overflow exception if there's
2262 not enough space left on the stack */
2263 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2264 return 0;
2265 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2266 EXCEPTION_EXECUTE_HANDLER :
2267 EXCEPTION_CONTINUE_SEARCH) {
2268 int errcode = _resetstkoflw();
2269 if (errcode == 0)
2270 {
2271 Py_FatalError("Could not reset the stack!");
2272 }
2273 }
2274 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002275}
2276
2277#endif /* WIN32 && _MSC_VER */
2278
2279/* Alternate implementations can be added here... */
2280
2281#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002282
2283
2284/* Wrappers around sigaction() or signal(). */
2285
2286PyOS_sighandler_t
2287PyOS_getsig(int sig)
2288{
2289#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002290 struct sigaction context;
2291 if (sigaction(sig, NULL, &context) == -1)
2292 return SIG_ERR;
2293 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002294#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002296/* Special signal handling for the secure CRT in Visual Studio 2005 */
2297#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 switch (sig) {
2299 /* Only these signals are valid */
2300 case SIGINT:
2301 case SIGILL:
2302 case SIGFPE:
2303 case SIGSEGV:
2304 case SIGTERM:
2305 case SIGBREAK:
2306 case SIGABRT:
2307 break;
2308 /* Don't call signal() with other values or it will assert */
2309 default:
2310 return SIG_ERR;
2311 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002312#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 handler = signal(sig, SIG_IGN);
2314 if (handler != SIG_ERR)
2315 signal(sig, handler);
2316 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002317#endif
2318}
2319
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002320/*
2321 * All of the code in this function must only use async-signal-safe functions,
2322 * listed at `man 7 signal` or
2323 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2324 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002325PyOS_sighandler_t
2326PyOS_setsig(int sig, PyOS_sighandler_t handler)
2327{
2328#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 /* Some code in Modules/signalmodule.c depends on sigaction() being
2330 * used here if HAVE_SIGACTION is defined. Fix that if this code
2331 * changes to invalidate that assumption.
2332 */
2333 struct sigaction context, ocontext;
2334 context.sa_handler = handler;
2335 sigemptyset(&context.sa_mask);
2336 context.sa_flags = 0;
2337 if (sigaction(sig, &context, &ocontext) == -1)
2338 return SIG_ERR;
2339 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002340#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 PyOS_sighandler_t oldhandler;
2342 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002343#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002345#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002347#endif
2348}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349
2350/* Deprecated C API functions still provided for binary compatiblity */
2351
2352#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002353PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002354PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002357}
2358
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002359#undef PyParser_SimpleParseString
2360PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361PyParser_SimpleParseString(const char *str, int start)
2362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002365
2366#undef PyRun_AnyFile
2367PyAPI_FUNC(int)
2368PyRun_AnyFile(FILE *fp, const char *name)
2369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002371}
2372
2373#undef PyRun_AnyFileEx
2374PyAPI_FUNC(int)
2375PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002378}
2379
2380#undef PyRun_AnyFileFlags
2381PyAPI_FUNC(int)
2382PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002385}
2386
2387#undef PyRun_File
2388PyAPI_FUNC(PyObject *)
2389PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002392}
2393
2394#undef PyRun_FileEx
2395PyAPI_FUNC(PyObject *)
2396PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002399}
2400
2401#undef PyRun_FileFlags
2402PyAPI_FUNC(PyObject *)
2403PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002407}
2408
2409#undef PyRun_SimpleFile
2410PyAPI_FUNC(int)
2411PyRun_SimpleFile(FILE *f, const char *p)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002414}
2415
2416#undef PyRun_SimpleFileEx
2417PyAPI_FUNC(int)
2418PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002421}
2422
2423
2424#undef PyRun_String
2425PyAPI_FUNC(PyObject *)
2426PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002429}
2430
2431#undef PyRun_SimpleString
2432PyAPI_FUNC(int)
2433PyRun_SimpleString(const char *s)
2434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002436}
2437
2438#undef Py_CompileString
2439PyAPI_FUNC(PyObject *)
2440Py_CompileString(const char *str, const char *p, int s)
2441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002443}
2444
2445#undef PyRun_InteractiveOne
2446PyAPI_FUNC(int)
2447PyRun_InteractiveOne(FILE *f, const char *p)
2448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002450}
2451
2452#undef PyRun_InteractiveLoop
2453PyAPI_FUNC(int)
2454PyRun_InteractiveLoop(FILE *f, const char *p)
2455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002457}
2458
2459#ifdef __cplusplus
2460}
2461#endif