blob: 37c1f1197aa746e540d5db30b552746ce001c064 [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);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000286 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000291
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000292 /* Initialize _warnings. */
293 _PyWarnings_Init();
294
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000295 _PyTime_Init();
296
Victor Stinnerb744ba12010-05-15 12:27:16 +0000297 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (install_sigs)
300 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 initmain(); /* Module __main__ */
303 if (initstdio() < 0)
304 Py_FatalError(
305 "Py_Initialize: can't initialize sys standard streams");
306
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000307 /* Initialize warnings. */
308 if (PySys_HasWarnOptions()) {
309 PyObject *warnings_module = PyImport_ImportModule("warnings");
310 if (warnings_module == NULL) {
311 fprintf(stderr, "'import warnings' failed; traceback:\n");
312 PyErr_Print();
313 }
314 Py_XDECREF(warnings_module);
315 }
316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 if (!Py_NoSiteFlag)
318 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000319}
320
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000321void
322Py_Initialize(void)
323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000325}
326
327
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000328#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000329extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000330#endif
331
Guido van Rossume8432ac2007-07-09 15:04:50 +0000332/* Flush stdout and stderr */
333
Neal Norwitz2bad9702007-08-27 06:19:22 +0000334static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000335flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 PyObject *fout = PySys_GetObject("stdout");
338 PyObject *ferr = PySys_GetObject("stderr");
339 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (fout != NULL && fout != Py_None) {
342 tmp = PyObject_CallMethod(fout, "flush", "");
343 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000344 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 else
346 Py_DECREF(tmp);
347 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000348
Victor Stinner9467b212010-05-14 00:59:09 +0000349 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 tmp = PyObject_CallMethod(ferr, "flush", "");
351 if (tmp == NULL)
352 PyErr_Clear();
353 else
354 Py_DECREF(tmp);
355 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000356}
357
Guido van Rossum25ce5661997-08-02 03:10:38 +0000358/* Undo the effect of Py_Initialize().
359
360 Beware: if multiple interpreter and/or thread states exist, these
361 are not wiped out; only the current thread and interpreter state
362 are deleted. But since everything else is deleted, those other
363 interpreter and thread states should no longer be used.
364
365 (XXX We should do better, e.g. wipe out all interpreters and
366 threads.)
367
368 Locking: as above.
369
370*/
371
372void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000373Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 PyInterpreterState *interp;
376 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 if (!initialized)
379 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 /* The interpreter is still entirely intact at this point, and the
384 * exit funcs may be relying on that. In particular, if some thread
385 * or exit func is still waiting to do an import, the import machinery
386 * expects Py_IsInitialized() to return true. So don't say the
387 * interpreter is uninitialized until after the exit funcs have run.
388 * Note that Threading.py uses an exit func to do a join on all the
389 * threads created thru it, so this also protects pending imports in
390 * the threads created via Threading.
391 */
392 call_py_exitfuncs();
393 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Flush stdout+stderr */
396 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 /* Get current thread state and interpreter pointer */
399 tstate = PyThreadState_GET();
400 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 /* Disable signal handling */
403 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 /* Clear type lookup cache */
406 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 /* Collect garbage. This may call finalizers; it's nice to call these
409 * before all modules are destroyed.
410 * XXX If a __del__ or weakref callback is triggered here, and tries to
411 * XXX import a module, bad things can happen, because Python no
412 * XXX longer believes it's initialized.
413 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
414 * XXX is easy to provoke that way. I've also seen, e.g.,
415 * XXX Exception exceptions.ImportError: 'No module named sha'
416 * XXX in <function callback at 0x008F5718> ignored
417 * XXX but I'm unclear on exactly how that one happens. In any case,
418 * XXX I haven't seen a real-life report of either of these.
419 */
420 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000421#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 /* With COUNT_ALLOCS, it helps to run GC multiple times:
423 each collection might release some types from the type
424 list, so they become garbage. */
425 while (PyGC_Collect() > 0)
426 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000427#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000428 /* We run this while most interpreter state is still alive, so that
429 debug information can be printed out */
430 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 /* Destroy all modules */
433 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* Flush stdout+stderr (again, in case more was printed) */
436 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 /* Collect final garbage. This disposes of cycles created by
439 * new-style class definitions, for example.
440 * XXX This is disabled because it caused too many problems. If
441 * XXX a __del__ or weakref callback triggers here, Python code has
442 * XXX a hard time running, because even the sys module has been
443 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
444 * XXX One symptom is a sequence of information-free messages
445 * XXX coming from threads (if a __del__ or callback is invoked,
446 * XXX other threads can execute too, and any exception they encounter
447 * XXX triggers a comedy of errors as subsystem after subsystem
448 * XXX fails to find what it *expects* to find in sys to help report
449 * XXX the exception and consequent unexpected failures). I've also
450 * XXX seen segfaults then, after adding print statements to the
451 * XXX Python code getting called.
452 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000453#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000455#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
458 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000461#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000463#endif
464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000466
Tim Peters9cf25ce2003-04-17 15:21:01 +0000467#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 /* Display all objects still alive -- this can invoke arbitrary
469 * __repr__ overrides, so requires a mostly-intact interpreter.
470 * Alas, a lot of stuff may still be alive now that will be cleaned
471 * up later.
472 */
473 if (Py_GETENV("PYTHONDUMPREFS"))
474 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000475#endif /* Py_TRACE_REFS */
476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 /* Clear interpreter state */
478 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 /* Now we decref the exception classes. After this point nothing
481 can raise an exception. That's okay, because each Fini() method
482 below has been checked to make sure no exceptions are ever
483 raised.
484 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000489#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000491#endif /* WITH_THREAD */
492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 /* Delete current thread */
494 PyThreadState_Swap(NULL);
495 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 /* Sundry finalizers */
498 PyMethod_Fini();
499 PyFrame_Fini();
500 PyCFunction_Fini();
501 PyTuple_Fini();
502 PyList_Fini();
503 PySet_Fini();
504 PyBytes_Fini();
505 PyByteArray_Fini();
506 PyLong_Fini();
507 PyFloat_Fini();
508 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* Cleanup Unicode implementation */
511 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000514 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 free((char*)Py_FileSystemDefaultEncoding);
516 Py_FileSystemDefaultEncoding = NULL;
517 }
Christian Heimesc8967002007-11-30 10:18:26 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 /* XXX Still allocated:
520 - various static ad-hoc pointers to interned strings
521 - int and float free list blocks
522 - whatever various modules and libraries allocate
523 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000526
Tim Peters269b2a62003-04-17 19:52:29 +0000527#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* Display addresses (& refcnts) of all objects still alive.
529 * An address can be used to find the repr of the object, printed
530 * above by _Py_PrintReferences.
531 */
532 if (Py_GETENV("PYTHONDUMPREFS"))
533 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000534#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000535#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 if (Py_GETENV("PYTHONMALLOCSTATS"))
537 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000538#endif
539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000541}
542
543/* Create and initialize a new interpreter and thread, and return the
544 new thread. This requires that Py_Initialize() has been called
545 first.
546
547 Unsuccessful initialization yields a NULL pointer. Note that *no*
548 exception information is available even in this case -- the
549 exception information is held in the thread, and there is no
550 thread.
551
552 Locking: as above.
553
554*/
555
556PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000557Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 PyInterpreterState *interp;
560 PyThreadState *tstate, *save_tstate;
561 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 if (!initialized)
564 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 interp = PyInterpreterState_New();
567 if (interp == NULL)
568 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 tstate = PyThreadState_New(interp);
571 if (tstate == NULL) {
572 PyInterpreterState_Delete(interp);
573 return NULL;
574 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 interp->modules = PyDict_New();
581 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000582
Victor Stinner49d3f252010-10-17 01:24:53 +0000583 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (bimod != NULL) {
585 interp->builtins = PyModule_GetDict(bimod);
586 if (interp->builtins == NULL)
587 goto handle_error;
588 Py_INCREF(interp->builtins);
589 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 /* initialize builtin exceptions */
592 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000593
Victor Stinner49d3f252010-10-17 01:24:53 +0000594 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (bimod != NULL && sysmod != NULL) {
596 PyObject *pstderr;
597 interp->sysdict = PyModule_GetDict(sysmod);
598 if (interp->sysdict == NULL)
599 goto handle_error;
600 Py_INCREF(interp->sysdict);
601 PySys_SetPath(Py_GetPath());
602 PyDict_SetItemString(interp->sysdict, "modules",
603 interp->modules);
604 /* Set up a preliminary stderr printer until we have enough
605 infrastructure for the io module in place. */
606 pstderr = PyFile_NewStdPrinter(fileno(stderr));
607 if (pstderr == NULL)
608 Py_FatalError("Py_Initialize: can't set preliminary stderr");
609 PySys_SetObject("stderr", pstderr);
610 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000611 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 _PyImportHooks_Init();
614 if (initstdio() < 0)
615 Py_FatalError(
616 "Py_Initialize: can't initialize sys standard streams");
617 initmain();
618 if (!Py_NoSiteFlag)
619 initsite();
620 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (!PyErr_Occurred())
623 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000624
Thomas Wouters89f507f2006-12-13 04:49:30 +0000625handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 PyErr_Print();
629 PyThreadState_Clear(tstate);
630 PyThreadState_Swap(save_tstate);
631 PyThreadState_Delete(tstate);
632 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635}
636
637/* Delete an interpreter and its last thread. This requires that the
638 given thread state is current, that the thread has no remaining
639 frames, and that it is its interpreter's only remaining thread.
640 It is a fatal error to violate these constraints.
641
642 (Py_Finalize() doesn't have these constraints -- it zaps
643 everything, regardless.)
644
645 Locking: as above.
646
647*/
648
649void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000650Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (tstate != PyThreadState_GET())
655 Py_FatalError("Py_EndInterpreter: thread is not current");
656 if (tstate->frame != NULL)
657 Py_FatalError("Py_EndInterpreter: thread still has a frame");
658 if (tstate != interp->tstate_head || tstate->next != NULL)
659 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyImport_Cleanup();
662 PyInterpreterState_Clear(interp);
663 PyThreadState_Swap(NULL);
664 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000665}
666
Martin v. Löwis790465f2008-04-05 20:41:37 +0000667static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000668
669void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000670Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 if (pn && *pn)
673 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000674}
675
Martin v. Löwis790465f2008-04-05 20:41:37 +0000676wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000677Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000680}
681
Martin v. Löwis790465f2008-04-05 20:41:37 +0000682static wchar_t *default_home = NULL;
683static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000684
685void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000686Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000689}
690
Martin v. Löwis790465f2008-04-05 20:41:37 +0000691wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000692Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 wchar_t *home = default_home;
695 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
696 char* chome = Py_GETENV("PYTHONHOME");
697 if (chome) {
698 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
699 if (r != (size_t)-1 && r <= PATH_MAX)
700 home = env_home;
701 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 }
704 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000705}
706
Guido van Rossum6135a871995-01-09 17:53:26 +0000707/* Create __main__ module */
708
709static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000710initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyObject *m, *d;
713 m = PyImport_AddModule("__main__");
714 if (m == NULL)
715 Py_FatalError("can't create __main__ module");
716 d = PyModule_GetDict(m);
717 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
718 PyObject *bimod = PyImport_ImportModule("builtins");
719 if (bimod == NULL ||
720 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
721 Py_FatalError("can't add __builtins__ to __main__");
722 Py_DECREF(bimod);
723 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000724}
725
Victor Stinnerb744ba12010-05-15 12:27:16 +0000726static void
727initfsencoding(void)
728{
729 PyObject *codec;
730#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000731 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000732
Victor Stinner7f84ab52010-06-11 00:36:33 +0000733 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000734 /* On Unix, set the file system encoding according to the
735 user's preference, if the CODESET names a well-known
736 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000737 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000738 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000739 if (codeset == NULL)
740 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000741
Victor Stinnere4743092010-10-19 00:05:51 +0000742 Py_FileSystemDefaultEncoding = codeset;
743 Py_HasFileSystemDefaultEncoding = 0;
744 return;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000745 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000746#endif
747
748 /* the encoding is mbcs, utf-8 or ascii */
749 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
750 if (!codec) {
751 /* Such error can only occurs in critical situations: no more
752 * memory, import a module of the standard library failed,
753 * etc. */
754 Py_FatalError("Py_Initialize: unable to load the file system codec");
755 } else {
756 Py_DECREF(codec);
757 }
758}
759
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000760/* Import the site module (not into __main__ though) */
761
762static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000763initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 PyObject *m;
766 m = PyImport_ImportModule("site");
767 if (m == NULL) {
768 PyErr_Print();
769 Py_Finalize();
770 exit(1);
771 }
772 else {
773 Py_DECREF(m);
774 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000775}
776
Antoine Pitrou05608432009-01-09 18:53:14 +0000777static PyObject*
778create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 int fd, int write_mode, char* name,
780 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
783 const char* mode;
784 PyObject *line_buffering;
785 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 /* stdin is always opened in buffered mode, first because it shouldn't
788 make a difference in common use cases, second because TextIOWrapper
789 depends on the presence of a read1() method which only exists on
790 buffered streams.
791 */
792 if (Py_UnbufferedStdioFlag && write_mode)
793 buffering = 0;
794 else
795 buffering = -1;
796 if (write_mode)
797 mode = "wb";
798 else
799 mode = "rb";
800 buf = PyObject_CallMethod(io, "open", "isiOOOi",
801 fd, mode, buffering,
802 Py_None, Py_None, Py_None, 0);
803 if (buf == NULL)
804 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 if (buffering) {
807 raw = PyObject_GetAttrString(buf, "raw");
808 if (raw == NULL)
809 goto error;
810 }
811 else {
812 raw = buf;
813 Py_INCREF(raw);
814 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 text = PyUnicode_FromString(name);
817 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
818 goto error;
819 res = PyObject_CallMethod(raw, "isatty", "");
820 if (res == NULL)
821 goto error;
822 isatty = PyObject_IsTrue(res);
823 Py_DECREF(res);
824 if (isatty == -1)
825 goto error;
826 if (isatty || Py_UnbufferedStdioFlag)
827 line_buffering = Py_True;
828 else
829 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 Py_CLEAR(raw);
832 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
835 buf, encoding, errors,
836 "\n", line_buffering);
837 Py_CLEAR(buf);
838 if (stream == NULL)
839 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (write_mode)
842 mode = "w";
843 else
844 mode = "r";
845 text = PyUnicode_FromString(mode);
846 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
847 goto error;
848 Py_CLEAR(text);
849 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000850
851error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 Py_XDECREF(buf);
853 Py_XDECREF(stream);
854 Py_XDECREF(text);
855 Py_XDECREF(raw);
856 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000857}
858
Georg Brandl1a3284e2007-12-02 09:40:06 +0000859/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000860static int
861initstdio(void)
862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 PyObject *iomod = NULL, *wrapper;
864 PyObject *bimod = NULL;
865 PyObject *m;
866 PyObject *std = NULL;
867 int status = 0, fd;
868 PyObject * encoding_attr;
869 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 /* Hack to avoid a nasty recursion issue when Python is invoked
872 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
873 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
874 goto error;
875 }
876 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
879 goto error;
880 }
881 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 if (!(bimod = PyImport_ImportModule("builtins"))) {
884 goto error;
885 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 if (!(iomod = PyImport_ImportModule("io"))) {
888 goto error;
889 }
890 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
891 goto error;
892 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Set builtins.open */
895 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000896 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 goto error;
898 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000899 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 encoding = Py_GETENV("PYTHONIOENCODING");
902 errors = NULL;
903 if (encoding) {
904 encoding = strdup(encoding);
905 errors = strchr(encoding, ':');
906 if (errors) {
907 *errors = '\0';
908 errors++;
909 }
910 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* Set sys.stdin */
913 fd = fileno(stdin);
914 /* Under some conditions stdin, stdout and stderr may not be connected
915 * and fileno() may point to an invalid file descriptor. For example
916 * GUI apps don't have valid standard streams by default.
917 */
918 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000919#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 std = Py_None;
921 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000922#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000924#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 }
926 else {
927 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
928 if (std == NULL)
929 goto error;
930 } /* if (fd < 0) */
931 PySys_SetObject("__stdin__", std);
932 PySys_SetObject("stdin", std);
933 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* Set sys.stdout */
936 fd = fileno(stdout);
937 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000938#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 std = Py_None;
940 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000941#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000943#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 }
945 else {
946 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
947 if (std == NULL)
948 goto error;
949 } /* if (fd < 0) */
950 PySys_SetObject("__stdout__", std);
951 PySys_SetObject("stdout", std);
952 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000953
Guido van Rossum98297ee2007-11-06 21:34:58 +0000954#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* Set sys.stderr, replaces the preliminary stderr */
956 fd = fileno(stderr);
957 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000958#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 std = Py_None;
960 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000961#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000963#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 }
965 else {
966 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
967 if (std == NULL)
968 goto error;
969 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Same as hack above, pre-import stderr's codec to avoid recursion
972 when import.c tries to write to stderr in verbose mode. */
973 encoding_attr = PyObject_GetAttrString(std, "encoding");
974 if (encoding_attr != NULL) {
975 const char * encoding;
976 encoding = _PyUnicode_AsString(encoding_attr);
977 if (encoding != NULL) {
978 _PyCodec_Lookup(encoding);
979 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000980 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 }
982 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 PySys_SetObject("__stderr__", std);
985 PySys_SetObject("stderr", std);
986 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000987#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000990 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 status = -1;
992 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 if (encoding)
995 free(encoding);
996 Py_XDECREF(bimod);
997 Py_XDECREF(iomod);
998 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000999}
1000
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001001/* Parse input from a file and execute it */
1002
1003int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001004PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (filename == NULL)
1008 filename = "???";
1009 if (Py_FdIsInteractive(fp, filename)) {
1010 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1011 if (closeit)
1012 fclose(fp);
1013 return err;
1014 }
1015 else
1016 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001017}
1018
1019int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001020PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 PyObject *v;
1023 int ret;
1024 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 if (flags == NULL) {
1027 flags = &local_flags;
1028 local_flags.cf_flags = 0;
1029 }
1030 v = PySys_GetObject("ps1");
1031 if (v == NULL) {
1032 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1033 Py_XDECREF(v);
1034 }
1035 v = PySys_GetObject("ps2");
1036 if (v == NULL) {
1037 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1038 Py_XDECREF(v);
1039 }
1040 for (;;) {
1041 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1042 PRINT_TOTAL_REFS();
1043 if (ret == E_EOF)
1044 return 0;
1045 /*
1046 if (ret == E_NOMEM)
1047 return -1;
1048 */
1049 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001050}
1051
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001052/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001053static int PARSER_FLAGS(PyCompilerFlags *flags)
1054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 int parser_flags = 0;
1056 if (!flags)
1057 return 0;
1058 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1059 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1060 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1061 parser_flags |= PyPARSE_IGNORE_COOKIE;
1062 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1063 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1064 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001065}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001066
Thomas Wouters89f507f2006-12-13 04:49:30 +00001067#if 0
1068/* Keep an example of flags with future keyword support. */
1069#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1071 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1072 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1073 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001074#endif
1075
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001076int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001077PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 PyObject *m, *d, *v, *w, *oenc = NULL;
1080 mod_ty mod;
1081 PyArena *arena;
1082 char *ps1 = "", *ps2 = "", *enc = NULL;
1083 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 if (fp == stdin) {
1086 /* Fetch encoding from sys.stdin */
1087 v = PySys_GetObject("stdin");
1088 if (v == NULL || v == Py_None)
1089 return -1;
1090 oenc = PyObject_GetAttrString(v, "encoding");
1091 if (!oenc)
1092 return -1;
1093 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001094 if (enc == NULL)
1095 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 }
1097 v = PySys_GetObject("ps1");
1098 if (v != NULL) {
1099 v = PyObject_Str(v);
1100 if (v == NULL)
1101 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001102 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001104 if (ps1 == NULL) {
1105 PyErr_Clear();
1106 ps1 = "";
1107 }
1108 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 }
1110 w = PySys_GetObject("ps2");
1111 if (w != NULL) {
1112 w = PyObject_Str(w);
1113 if (w == NULL)
1114 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001115 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001117 if (ps2 == NULL) {
1118 PyErr_Clear();
1119 ps2 = "";
1120 }
1121 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 }
1123 arena = PyArena_New();
1124 if (arena == NULL) {
1125 Py_XDECREF(v);
1126 Py_XDECREF(w);
1127 Py_XDECREF(oenc);
1128 return -1;
1129 }
1130 mod = PyParser_ASTFromFile(fp, filename, enc,
1131 Py_single_input, ps1, ps2,
1132 flags, &errcode, arena);
1133 Py_XDECREF(v);
1134 Py_XDECREF(w);
1135 Py_XDECREF(oenc);
1136 if (mod == NULL) {
1137 PyArena_Free(arena);
1138 if (errcode == E_EOF) {
1139 PyErr_Clear();
1140 return E_EOF;
1141 }
1142 PyErr_Print();
1143 return -1;
1144 }
1145 m = PyImport_AddModule("__main__");
1146 if (m == NULL) {
1147 PyArena_Free(arena);
1148 return -1;
1149 }
1150 d = PyModule_GetDict(m);
1151 v = run_mod(mod, filename, d, d, flags, arena);
1152 PyArena_Free(arena);
1153 flush_io();
1154 if (v == NULL) {
1155 PyErr_Print();
1156 return -1;
1157 }
1158 Py_DECREF(v);
1159 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001160}
1161
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001162/* Check whether a file maybe a pyc file: Look at the extension,
1163 the file type, and, if we may close it, at the first few bytes. */
1164
1165static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001166maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1169 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 /* Only look into the file if we are allowed to close it, since
1172 it then should also be seekable. */
1173 if (closeit) {
1174 /* Read only two bytes of the magic. If the file was opened in
1175 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1176 be read as they are on disk. */
1177 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1178 unsigned char buf[2];
1179 /* Mess: In case of -x, the stream is NOT at its start now,
1180 and ungetc() was used to push back the first newline,
1181 which makes the current stream position formally undefined,
1182 and a x-platform nightmare.
1183 Unfortunately, we have no direct way to know whether -x
1184 was specified. So we use a terrible hack: if the current
1185 stream position is not 0, we assume -x was specified, and
1186 give up. Bug 132850 on SourceForge spells out the
1187 hopelessness of trying anything else (fseek and ftell
1188 don't work predictably x-platform for text-mode files).
1189 */
1190 int ispyc = 0;
1191 if (ftell(fp) == 0) {
1192 if (fread(buf, 1, 2, fp) == 2 &&
1193 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1194 ispyc = 1;
1195 rewind(fp);
1196 }
1197 return ispyc;
1198 }
1199 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001200}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001201
Guido van Rossum0df002c2000-08-27 19:21:52 +00001202int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001203PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 PyObject *m, *d, *v;
1207 const char *ext;
1208 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 m = PyImport_AddModule("__main__");
1211 if (m == NULL)
1212 return -1;
1213 d = PyModule_GetDict(m);
1214 if (PyDict_GetItemString(d, "__file__") == NULL) {
1215 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001216 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (f == NULL)
1218 return -1;
1219 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1220 Py_DECREF(f);
1221 return -1;
1222 }
1223 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1224 return -1;
1225 set_file_name = 1;
1226 Py_DECREF(f);
1227 }
1228 len = strlen(filename);
1229 ext = filename + len - (len > 4 ? 4 : 0);
1230 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1231 /* Try to run a pyc file. First, re-open in binary */
1232 if (closeit)
1233 fclose(fp);
1234 if ((fp = fopen(filename, "rb")) == NULL) {
1235 fprintf(stderr, "python: Can't reopen .pyc file\n");
1236 ret = -1;
1237 goto done;
1238 }
1239 /* Turn on optimization if a .pyo file is given */
1240 if (strcmp(ext, ".pyo") == 0)
1241 Py_OptimizeFlag = 1;
1242 v = run_pyc_file(fp, filename, d, d, flags);
1243 } else {
1244 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1245 closeit, flags);
1246 }
1247 flush_io();
1248 if (v == NULL) {
1249 PyErr_Print();
1250 ret = -1;
1251 goto done;
1252 }
1253 Py_DECREF(v);
1254 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001255 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1257 PyErr_Clear();
1258 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001259}
1260
1261int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001262PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 PyObject *m, *d, *v;
1265 m = PyImport_AddModule("__main__");
1266 if (m == NULL)
1267 return -1;
1268 d = PyModule_GetDict(m);
1269 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1270 if (v == NULL) {
1271 PyErr_Print();
1272 return -1;
1273 }
1274 Py_DECREF(v);
1275 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001276}
1277
Barry Warsaw035574d1997-08-29 22:07:17 +00001278static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001279parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 long hold;
1283 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 /* old style errors */
1286 if (PyTuple_Check(err))
1287 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1288 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (! (v = PyObject_GetAttrString(err, "msg")))
1293 goto finally;
1294 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (!(v = PyObject_GetAttrString(err, "filename")))
1297 goto finally;
1298 if (v == Py_None)
1299 *filename = NULL;
1300 else if (! (*filename = _PyUnicode_AsString(v)))
1301 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 Py_DECREF(v);
1304 if (!(v = PyObject_GetAttrString(err, "lineno")))
1305 goto finally;
1306 hold = PyLong_AsLong(v);
1307 Py_DECREF(v);
1308 v = NULL;
1309 if (hold < 0 && PyErr_Occurred())
1310 goto finally;
1311 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (!(v = PyObject_GetAttrString(err, "offset")))
1314 goto finally;
1315 if (v == Py_None) {
1316 *offset = -1;
1317 Py_DECREF(v);
1318 v = NULL;
1319 } else {
1320 hold = PyLong_AsLong(v);
1321 Py_DECREF(v);
1322 v = NULL;
1323 if (hold < 0 && PyErr_Occurred())
1324 goto finally;
1325 *offset = (int)hold;
1326 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 if (!(v = PyObject_GetAttrString(err, "text")))
1329 goto finally;
1330 if (v == Py_None)
1331 *text = NULL;
1332 else if (!PyUnicode_Check(v) ||
1333 !(*text = _PyUnicode_AsString(v)))
1334 goto finally;
1335 Py_DECREF(v);
1336 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001337
1338finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 Py_XDECREF(v);
1340 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001341}
1342
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001343void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001344PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001347}
1348
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001349static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001350print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 char *nl;
1353 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001354 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1355 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 for (;;) {
1357 nl = strchr(text, '\n');
1358 if (nl == NULL || nl-text >= offset)
1359 break;
1360 offset -= (int)(nl+1-text);
1361 text = nl+1;
1362 }
1363 while (*text == ' ' || *text == '\t') {
1364 text++;
1365 offset--;
1366 }
1367 }
1368 PyFile_WriteString(" ", f);
1369 PyFile_WriteString(text, f);
1370 if (*text == '\0' || text[strlen(text)-1] != '\n')
1371 PyFile_WriteString("\n", f);
1372 if (offset == -1)
1373 return;
1374 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001375 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001378}
1379
Guido van Rossum66e8e862001-03-23 17:54:43 +00001380static void
1381handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 PyObject *exception, *value, *tb;
1384 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 if (Py_InspectFlag)
1387 /* Don't exit if -i flag was given. This flag is set to 0
1388 * when entering interactive mode for inspecting. */
1389 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 PyErr_Fetch(&exception, &value, &tb);
1392 fflush(stdout);
1393 if (value == NULL || value == Py_None)
1394 goto done;
1395 if (PyExceptionInstance_Check(value)) {
1396 /* The error code should be in the `code' attribute. */
1397 PyObject *code = PyObject_GetAttrString(value, "code");
1398 if (code) {
1399 Py_DECREF(value);
1400 value = code;
1401 if (value == Py_None)
1402 goto done;
1403 }
1404 /* If we failed to dig out the 'code' attribute,
1405 just let the else clause below print the error. */
1406 }
1407 if (PyLong_Check(value))
1408 exitcode = (int)PyLong_AsLong(value);
1409 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001410 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001411 if (sys_stderr != NULL && sys_stderr != Py_None) {
1412 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1413 } else {
1414 PyObject_Print(value, stderr, Py_PRINT_RAW);
1415 fflush(stderr);
1416 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 PySys_WriteStderr("\n");
1418 exitcode = 1;
1419 }
Tim Peterscf615b52003-04-19 18:47:02 +00001420 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 /* Restore and clear the exception info, in order to properly decref
1422 * the exception, value, and traceback. If we just exit instead,
1423 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1424 * some finalizers from running.
1425 */
1426 PyErr_Restore(exception, value, tb);
1427 PyErr_Clear();
1428 Py_Exit(exitcode);
1429 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001430}
1431
1432void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001433PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1438 handle_system_exit();
1439 }
1440 PyErr_Fetch(&exception, &v, &tb);
1441 if (exception == NULL)
1442 return;
1443 PyErr_NormalizeException(&exception, &v, &tb);
1444 if (tb == NULL) {
1445 tb = Py_None;
1446 Py_INCREF(tb);
1447 }
1448 PyException_SetTraceback(v, tb);
1449 if (exception == NULL)
1450 return;
1451 /* Now we know v != NULL too */
1452 if (set_sys_last_vars) {
1453 PySys_SetObject("last_type", exception);
1454 PySys_SetObject("last_value", v);
1455 PySys_SetObject("last_traceback", tb);
1456 }
1457 hook = PySys_GetObject("excepthook");
1458 if (hook) {
1459 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1460 PyObject *result = PyEval_CallObject(hook, args);
1461 if (result == NULL) {
1462 PyObject *exception2, *v2, *tb2;
1463 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1464 handle_system_exit();
1465 }
1466 PyErr_Fetch(&exception2, &v2, &tb2);
1467 PyErr_NormalizeException(&exception2, &v2, &tb2);
1468 /* It should not be possible for exception2 or v2
1469 to be NULL. However PyErr_Display() can't
1470 tolerate NULLs, so just be safe. */
1471 if (exception2 == NULL) {
1472 exception2 = Py_None;
1473 Py_INCREF(exception2);
1474 }
1475 if (v2 == NULL) {
1476 v2 = Py_None;
1477 Py_INCREF(v2);
1478 }
1479 fflush(stdout);
1480 PySys_WriteStderr("Error in sys.excepthook:\n");
1481 PyErr_Display(exception2, v2, tb2);
1482 PySys_WriteStderr("\nOriginal exception was:\n");
1483 PyErr_Display(exception, v, tb);
1484 Py_DECREF(exception2);
1485 Py_DECREF(v2);
1486 Py_XDECREF(tb2);
1487 }
1488 Py_XDECREF(result);
1489 Py_XDECREF(args);
1490 } else {
1491 PySys_WriteStderr("sys.excepthook is missing\n");
1492 PyErr_Display(exception, v, tb);
1493 }
1494 Py_XDECREF(exception);
1495 Py_XDECREF(v);
1496 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001497}
1498
Benjamin Petersone6528212008-07-15 15:32:09 +00001499static void
1500print_exception(PyObject *f, PyObject *value)
1501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 int err = 0;
1503 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 if (!PyExceptionInstance_Check(value)) {
1506 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1507 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1508 PyFile_WriteString(" found\n", f);
1509 return;
1510 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 Py_INCREF(value);
1513 fflush(stdout);
1514 type = (PyObject *) Py_TYPE(value);
1515 tb = PyException_GetTraceback(value);
1516 if (tb && tb != Py_None)
1517 err = PyTraceBack_Print(tb, f);
1518 if (err == 0 &&
1519 PyObject_HasAttrString(value, "print_file_and_line"))
1520 {
1521 PyObject *message;
1522 const char *filename, *text;
1523 int lineno, offset;
1524 if (!parse_syntax_error(value, &message, &filename,
1525 &lineno, &offset, &text))
1526 PyErr_Clear();
1527 else {
1528 char buf[10];
1529 PyFile_WriteString(" File \"", f);
1530 if (filename == NULL)
1531 PyFile_WriteString("<string>", f);
1532 else
1533 PyFile_WriteString(filename, f);
1534 PyFile_WriteString("\", line ", f);
1535 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1536 PyFile_WriteString(buf, f);
1537 PyFile_WriteString("\n", f);
1538 if (text != NULL)
1539 print_error_text(f, offset, text);
1540 Py_DECREF(value);
1541 value = message;
1542 /* Can't be bothered to check all those
1543 PyFile_WriteString() calls */
1544 if (PyErr_Occurred())
1545 err = -1;
1546 }
1547 }
1548 if (err) {
1549 /* Don't do anything else */
1550 }
1551 else {
1552 PyObject* moduleName;
1553 char* className;
1554 assert(PyExceptionClass_Check(type));
1555 className = PyExceptionClass_Name(type);
1556 if (className != NULL) {
1557 char *dot = strrchr(className, '.');
1558 if (dot != NULL)
1559 className = dot+1;
1560 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 moduleName = PyObject_GetAttrString(type, "__module__");
1563 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1564 {
1565 Py_DECREF(moduleName);
1566 err = PyFile_WriteString("<unknown>", f);
1567 }
1568 else {
1569 char* modstr = _PyUnicode_AsString(moduleName);
1570 if (modstr && strcmp(modstr, "builtins"))
1571 {
1572 err = PyFile_WriteString(modstr, f);
1573 err += PyFile_WriteString(".", f);
1574 }
1575 Py_DECREF(moduleName);
1576 }
1577 if (err == 0) {
1578 if (className == NULL)
1579 err = PyFile_WriteString("<unknown>", f);
1580 else
1581 err = PyFile_WriteString(className, f);
1582 }
1583 }
1584 if (err == 0 && (value != Py_None)) {
1585 PyObject *s = PyObject_Str(value);
1586 /* only print colon if the str() of the
1587 object is not the empty string
1588 */
1589 if (s == NULL)
1590 err = -1;
1591 else if (!PyUnicode_Check(s) ||
1592 PyUnicode_GetSize(s) != 0)
1593 err = PyFile_WriteString(": ", f);
1594 if (err == 0)
1595 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1596 Py_XDECREF(s);
1597 }
1598 /* try to write a newline in any case */
1599 err += PyFile_WriteString("\n", f);
1600 Py_XDECREF(tb);
1601 Py_DECREF(value);
1602 /* If an error happened here, don't show it.
1603 XXX This is wrong, but too many callers rely on this behavior. */
1604 if (err != 0)
1605 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001606}
1607
1608static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 "\nThe above exception was the direct cause "
1610 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001611
1612static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 "\nDuring handling of the above exception, "
1614 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001615
1616static void
1617print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 int err = 0, res;
1620 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (seen != NULL) {
1623 /* Exception chaining */
1624 if (PySet_Add(seen, value) == -1)
1625 PyErr_Clear();
1626 else if (PyExceptionInstance_Check(value)) {
1627 cause = PyException_GetCause(value);
1628 context = PyException_GetContext(value);
1629 if (cause) {
1630 res = PySet_Contains(seen, cause);
1631 if (res == -1)
1632 PyErr_Clear();
1633 if (res == 0) {
1634 print_exception_recursive(
1635 f, cause, seen);
1636 err |= PyFile_WriteString(
1637 cause_message, f);
1638 }
1639 }
1640 else if (context) {
1641 res = PySet_Contains(seen, context);
1642 if (res == -1)
1643 PyErr_Clear();
1644 if (res == 0) {
1645 print_exception_recursive(
1646 f, context, seen);
1647 err |= PyFile_WriteString(
1648 context_message, f);
1649 }
1650 }
1651 Py_XDECREF(context);
1652 Py_XDECREF(cause);
1653 }
1654 }
1655 print_exception(f, value);
1656 if (err != 0)
1657 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001658}
1659
Thomas Wouters477c8d52006-05-27 19:21:47 +00001660void
1661PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 PyObject *seen;
1664 PyObject *f = PySys_GetObject("stderr");
1665 if (f == Py_None) {
1666 /* pass */
1667 }
1668 else if (f == NULL) {
1669 _PyObject_Dump(value);
1670 fprintf(stderr, "lost sys.stderr\n");
1671 }
1672 else {
1673 /* We choose to ignore seen being possibly NULL, and report
1674 at least the main exception (it could be a MemoryError).
1675 */
1676 seen = PySet_New(NULL);
1677 if (seen == NULL)
1678 PyErr_Clear();
1679 print_exception_recursive(f, value, seen);
1680 Py_XDECREF(seen);
1681 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001682}
1683
Guido van Rossum82598051997-03-05 00:20:32 +00001684PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001685PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PyObject *ret = NULL;
1689 mod_ty mod;
1690 PyArena *arena = PyArena_New();
1691 if (arena == NULL)
1692 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1695 if (mod != NULL)
1696 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1697 PyArena_Free(arena);
1698 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001699}
1700
1701PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001702PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyObject *ret;
1706 mod_ty mod;
1707 PyArena *arena = PyArena_New();
1708 if (arena == NULL)
1709 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1712 flags, NULL, arena);
1713 if (closeit)
1714 fclose(fp);
1715 if (mod == NULL) {
1716 PyArena_Free(arena);
1717 return NULL;
1718 }
1719 ret = run_mod(mod, filename, globals, locals, flags, arena);
1720 PyArena_Free(arena);
1721 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001722}
1723
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001724static void
1725flush_io(void)
1726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyObject *f, *r;
1728 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 /* Save the current exception */
1731 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 f = PySys_GetObject("stderr");
1734 if (f != NULL) {
1735 r = PyObject_CallMethod(f, "flush", "");
1736 if (r)
1737 Py_DECREF(r);
1738 else
1739 PyErr_Clear();
1740 }
1741 f = PySys_GetObject("stdout");
1742 if (f != NULL) {
1743 r = PyObject_CallMethod(f, "flush", "");
1744 if (r)
1745 Py_DECREF(r);
1746 else
1747 PyErr_Clear();
1748 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001751}
1752
Guido van Rossum82598051997-03-05 00:20:32 +00001753static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001754run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyCodeObject *co;
1758 PyObject *v;
1759 co = PyAST_Compile(mod, filename, flags, arena);
1760 if (co == NULL)
1761 return NULL;
1762 v = PyEval_EvalCode(co, globals, locals);
1763 Py_DECREF(co);
1764 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001765}
1766
Guido van Rossum82598051997-03-05 00:20:32 +00001767static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001768run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyCodeObject *co;
1772 PyObject *v;
1773 long magic;
1774 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 magic = PyMarshal_ReadLongFromFile(fp);
1777 if (magic != PyImport_GetMagicNumber()) {
1778 PyErr_SetString(PyExc_RuntimeError,
1779 "Bad magic number in .pyc file");
1780 return NULL;
1781 }
1782 (void) PyMarshal_ReadLongFromFile(fp);
1783 v = PyMarshal_ReadLastObjectFromFile(fp);
1784 fclose(fp);
1785 if (v == NULL || !PyCode_Check(v)) {
1786 Py_XDECREF(v);
1787 PyErr_SetString(PyExc_RuntimeError,
1788 "Bad code object in .pyc file");
1789 return NULL;
1790 }
1791 co = (PyCodeObject *)v;
1792 v = PyEval_EvalCode(co, globals, locals);
1793 if (v && flags)
1794 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1795 Py_DECREF(co);
1796 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001797}
1798
Guido van Rossum82598051997-03-05 00:20:32 +00001799PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001800Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 PyCodeObject *co;
1804 mod_ty mod;
1805 PyArena *arena = PyArena_New();
1806 if (arena == NULL)
1807 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1810 if (mod == NULL) {
1811 PyArena_Free(arena);
1812 return NULL;
1813 }
1814 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1815 PyObject *result = PyAST_mod2obj(mod);
1816 PyArena_Free(arena);
1817 return result;
1818 }
1819 co = PyAST_Compile(mod, filename, flags, arena);
1820 PyArena_Free(arena);
1821 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001822}
1823
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001824struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001825Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 struct symtable *st;
1828 mod_ty mod;
1829 PyCompilerFlags flags;
1830 PyArena *arena = PyArena_New();
1831 if (arena == NULL)
1832 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 flags.cf_flags = 0;
1835 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1836 if (mod == NULL) {
1837 PyArena_Free(arena);
1838 return NULL;
1839 }
1840 st = PySymtable_Build(mod, filename, 0);
1841 PyArena_Free(arena);
1842 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001843}
1844
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001845/* Preferred access to parser is through AST. */
1846mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001847PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 mod_ty mod;
1851 PyCompilerFlags localflags;
1852 perrdetail err;
1853 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1856 &_PyParser_Grammar, start, &err,
1857 &iflags);
1858 if (flags == NULL) {
1859 localflags.cf_flags = 0;
1860 flags = &localflags;
1861 }
1862 if (n) {
1863 flags->cf_flags |= iflags & PyCF_MASK;
1864 mod = PyAST_FromNode(n, flags, filename, arena);
1865 PyNode_Free(n);
1866 return mod;
1867 }
1868 else {
1869 err_input(&err);
1870 return NULL;
1871 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001872}
1873
1874mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001875PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 int start, char *ps1,
1877 char *ps2, PyCompilerFlags *flags, int *errcode,
1878 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 mod_ty mod;
1881 PyCompilerFlags localflags;
1882 perrdetail err;
1883 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1886 &_PyParser_Grammar,
1887 start, ps1, ps2, &err, &iflags);
1888 if (flags == NULL) {
1889 localflags.cf_flags = 0;
1890 flags = &localflags;
1891 }
1892 if (n) {
1893 flags->cf_flags |= iflags & PyCF_MASK;
1894 mod = PyAST_FromNode(n, flags, filename, arena);
1895 PyNode_Free(n);
1896 return mod;
1897 }
1898 else {
1899 err_input(&err);
1900 if (errcode)
1901 *errcode = err.error;
1902 return NULL;
1903 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904}
1905
Guido van Rossuma110aa61994-08-29 12:50:44 +00001906/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001907
Guido van Rossuma110aa61994-08-29 12:50:44 +00001908node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001909PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 perrdetail err;
1912 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1913 &_PyParser_Grammar,
1914 start, NULL, NULL, &err, flags);
1915 if (n == NULL)
1916 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001919}
1920
Guido van Rossuma110aa61994-08-29 12:50:44 +00001921/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001922
Guido van Rossuma110aa61994-08-29 12:50:44 +00001923node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001924PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 perrdetail err;
1927 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1928 start, &err, flags);
1929 if (n == NULL)
1930 err_input(&err);
1931 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001932}
1933
1934node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001935PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 perrdetail err;
1939 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1940 &_PyParser_Grammar, start, &err, flags);
1941 if (n == NULL)
1942 err_input(&err);
1943 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001944}
1945
1946node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001947PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001950}
1951
Guido van Rossum66ebd912003-04-17 16:02:26 +00001952/* May want to move a more generalized form of this to parsetok.c or
1953 even parser modules. */
1954
1955void
1956PyParser_SetError(perrdetail *err)
1957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001959}
1960
Guido van Rossuma110aa61994-08-29 12:50:44 +00001961/* Set the error appropriate to the given input error code (see errcode.h) */
1962
1963static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001964err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 PyObject *v, *w, *errtype, *errtext;
1967 PyObject *msg_obj = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001968 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 errtype = PyExc_SyntaxError;
1972 switch (err->error) {
1973 case E_ERROR:
1974 return;
1975 case E_SYNTAX:
1976 errtype = PyExc_IndentationError;
1977 if (err->expected == INDENT)
1978 msg = "expected an indented block";
1979 else if (err->token == INDENT)
1980 msg = "unexpected indent";
1981 else if (err->token == DEDENT)
1982 msg = "unexpected unindent";
1983 else {
1984 errtype = PyExc_SyntaxError;
1985 msg = "invalid syntax";
1986 }
1987 break;
1988 case E_TOKEN:
1989 msg = "invalid token";
1990 break;
1991 case E_EOFS:
1992 msg = "EOF while scanning triple-quoted string literal";
1993 break;
1994 case E_EOLS:
1995 msg = "EOL while scanning string literal";
1996 break;
1997 case E_INTR:
1998 if (!PyErr_Occurred())
1999 PyErr_SetNone(PyExc_KeyboardInterrupt);
2000 goto cleanup;
2001 case E_NOMEM:
2002 PyErr_NoMemory();
2003 goto cleanup;
2004 case E_EOF:
2005 msg = "unexpected EOF while parsing";
2006 break;
2007 case E_TABSPACE:
2008 errtype = PyExc_TabError;
2009 msg = "inconsistent use of tabs and spaces in indentation";
2010 break;
2011 case E_OVERFLOW:
2012 msg = "expression too long";
2013 break;
2014 case E_DEDENT:
2015 errtype = PyExc_IndentationError;
2016 msg = "unindent does not match any outer indentation level";
2017 break;
2018 case E_TOODEEP:
2019 errtype = PyExc_IndentationError;
2020 msg = "too many levels of indentation";
2021 break;
2022 case E_DECODE: {
2023 PyObject *type, *value, *tb;
2024 PyErr_Fetch(&type, &value, &tb);
2025 msg = "unknown decode error";
2026 if (value != NULL)
2027 msg_obj = PyObject_Str(value);
2028 Py_XDECREF(type);
2029 Py_XDECREF(value);
2030 Py_XDECREF(tb);
2031 break;
2032 }
2033 case E_LINECONT:
2034 msg = "unexpected character after line continuation character";
2035 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 case E_IDENTIFIER:
2038 msg = "invalid character in identifier";
2039 break;
2040 default:
2041 fprintf(stderr, "error=%d\n", err->error);
2042 msg = "unknown parsing error";
2043 break;
2044 }
2045 /* err->text may not be UTF-8 in case of decoding errors.
2046 Explicitly convert to an object. */
2047 if (!err->text) {
2048 errtext = Py_None;
2049 Py_INCREF(Py_None);
2050 } else {
2051 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2052 "replace");
2053 }
Victor Stinner2f2ed1f2010-10-16 13:42:53 +00002054 if (err->filename != NULL)
2055 filename = PyUnicode_DecodeFSDefault(err->filename);
2056 else {
2057 Py_INCREF(Py_None);
2058 filename = Py_None;
2059 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002060 if (filename != NULL)
2061 v = Py_BuildValue("(NiiN)", filename,
2062 err->lineno, err->offset, errtext);
2063 else
2064 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 if (v != NULL) {
2066 if (msg_obj)
2067 w = Py_BuildValue("(OO)", msg_obj, v);
2068 else
2069 w = Py_BuildValue("(sO)", msg, v);
2070 } else
2071 w = NULL;
2072 Py_XDECREF(v);
2073 PyErr_SetObject(errtype, w);
2074 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002075cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 Py_XDECREF(msg_obj);
2077 if (err->text != NULL) {
2078 PyObject_FREE(err->text);
2079 err->text = NULL;
2080 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002081}
2082
2083/* Print fatal error message and abort */
2084
2085void
Tim Peters7c321a82002-07-09 02:57:01 +00002086Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 fprintf(stderr, "Fatal Python error: %s\n", msg);
2089 fflush(stderr); /* it helps in Windows debug build */
2090 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002091 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002093#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 {
2095 size_t len = strlen(msg);
2096 WCHAR* buffer;
2097 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 /* Convert the message to wchar_t. This uses a simple one-to-one
2100 conversion, assuming that the this error message actually uses ASCII
2101 only. If this ceases to be true, we will have to convert. */
2102 buffer = alloca( (len+1) * (sizeof *buffer));
2103 for( i=0; i<=len; ++i)
2104 buffer[i] = msg[i];
2105 OutputDebugStringW(L"Fatal Python error: ");
2106 OutputDebugStringW(buffer);
2107 OutputDebugStringW(L"\n");
2108 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002109#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002111#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002112#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002114}
2115
2116/* Clean up and exit */
2117
Guido van Rossuma110aa61994-08-29 12:50:44 +00002118#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002119#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002120#endif
2121
Collin Winter670e6922007-03-21 02:57:17 +00002122static void (*pyexitfunc)(void) = NULL;
2123/* For the atexit module. */
2124void _Py_PyAtExit(void (*func)(void))
2125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002127}
2128
2129static void
2130call_py_exitfuncs(void)
2131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 if (pyexitfunc == NULL)
2133 return;
Collin Winter670e6922007-03-21 02:57:17 +00002134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 (*pyexitfunc)();
2136 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002137}
2138
Antoine Pitrou011bd622009-10-20 21:52:47 +00002139/* Wait until threading._shutdown completes, provided
2140 the threading module was imported in the first place.
2141 The shutdown routine will wait until all non-daemon
2142 "threading" threads have completed. */
2143static void
2144wait_for_thread_shutdown(void)
2145{
2146#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 PyObject *result;
2148 PyThreadState *tstate = PyThreadState_GET();
2149 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2150 "threading");
2151 if (threading == NULL) {
2152 /* threading not imported */
2153 PyErr_Clear();
2154 return;
2155 }
2156 result = PyObject_CallMethod(threading, "_shutdown", "");
2157 if (result == NULL) {
2158 PyErr_WriteUnraisable(threading);
2159 }
2160 else {
2161 Py_DECREF(result);
2162 }
2163 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002164#endif
2165}
2166
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002167#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002168static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002169static int nexitfuncs = 0;
2170
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002171int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 if (nexitfuncs >= NEXITFUNCS)
2174 return -1;
2175 exitfuncs[nexitfuncs++] = func;
2176 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002177}
2178
Guido van Rossumcc283f51997-08-05 02:22:03 +00002179static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002180call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 while (nexitfuncs > 0)
2183 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 fflush(stdout);
2186 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002187}
2188
2189void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002190Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002195}
2196
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002197static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002198initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002199{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002200#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002202#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002203#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002205#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002206#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002208#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002210}
2211
Guido van Rossum7433b121997-02-14 19:45:36 +00002212
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002213/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2214 *
2215 * All of the code in this function must only use async-signal-safe functions,
2216 * listed at `man 7 signal` or
2217 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2218 */
2219void
2220_Py_RestoreSignals(void)
2221{
2222#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002224#endif
2225#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002227#endif
2228#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002230#endif
2231}
2232
2233
Guido van Rossum7433b121997-02-14 19:45:36 +00002234/*
2235 * The file descriptor fd is considered ``interactive'' if either
2236 * a) isatty(fd) is TRUE, or
2237 * b) the -i flag was given, and the filename associated with
2238 * the descriptor is NULL or "<stdin>" or "???".
2239 */
2240int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002241Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 if (isatty((int)fileno(fp)))
2244 return 1;
2245 if (!Py_InteractiveFlag)
2246 return 0;
2247 return (filename == NULL) ||
2248 (strcmp(filename, "<stdin>") == 0) ||
2249 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002250}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002251
2252
Tim Petersd08e3822003-04-17 15:24:21 +00002253#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002254#if defined(WIN32) && defined(_MSC_VER)
2255
2256/* Stack checking for Microsoft C */
2257
2258#include <malloc.h>
2259#include <excpt.h>
2260
Fred Drakee8de31c2000-08-31 05:38:39 +00002261/*
2262 * Return non-zero when we run out of memory on the stack; zero otherwise.
2263 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002264int
Fred Drake399739f2000-08-31 05:52:44 +00002265PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 __try {
2268 /* alloca throws a stack overflow exception if there's
2269 not enough space left on the stack */
2270 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2271 return 0;
2272 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2273 EXCEPTION_EXECUTE_HANDLER :
2274 EXCEPTION_CONTINUE_SEARCH) {
2275 int errcode = _resetstkoflw();
2276 if (errcode == 0)
2277 {
2278 Py_FatalError("Could not reset the stack!");
2279 }
2280 }
2281 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002282}
2283
2284#endif /* WIN32 && _MSC_VER */
2285
2286/* Alternate implementations can be added here... */
2287
2288#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002289
2290
2291/* Wrappers around sigaction() or signal(). */
2292
2293PyOS_sighandler_t
2294PyOS_getsig(int sig)
2295{
2296#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 struct sigaction context;
2298 if (sigaction(sig, NULL, &context) == -1)
2299 return SIG_ERR;
2300 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002301#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002303/* Special signal handling for the secure CRT in Visual Studio 2005 */
2304#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 switch (sig) {
2306 /* Only these signals are valid */
2307 case SIGINT:
2308 case SIGILL:
2309 case SIGFPE:
2310 case SIGSEGV:
2311 case SIGTERM:
2312 case SIGBREAK:
2313 case SIGABRT:
2314 break;
2315 /* Don't call signal() with other values or it will assert */
2316 default:
2317 return SIG_ERR;
2318 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002319#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 handler = signal(sig, SIG_IGN);
2321 if (handler != SIG_ERR)
2322 signal(sig, handler);
2323 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002324#endif
2325}
2326
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002327/*
2328 * All of the code in this function must only use async-signal-safe functions,
2329 * listed at `man 7 signal` or
2330 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2331 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002332PyOS_sighandler_t
2333PyOS_setsig(int sig, PyOS_sighandler_t handler)
2334{
2335#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 /* Some code in Modules/signalmodule.c depends on sigaction() being
2337 * used here if HAVE_SIGACTION is defined. Fix that if this code
2338 * changes to invalidate that assumption.
2339 */
2340 struct sigaction context, ocontext;
2341 context.sa_handler = handler;
2342 sigemptyset(&context.sa_mask);
2343 context.sa_flags = 0;
2344 if (sigaction(sig, &context, &ocontext) == -1)
2345 return SIG_ERR;
2346 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002347#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 PyOS_sighandler_t oldhandler;
2349 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002350#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002352#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002354#endif
2355}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356
2357/* Deprecated C API functions still provided for binary compatiblity */
2358
2359#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002360PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002361PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002364}
2365
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002366#undef PyParser_SimpleParseString
2367PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002368PyParser_SimpleParseString(const char *str, int start)
2369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002371}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002372
2373#undef PyRun_AnyFile
2374PyAPI_FUNC(int)
2375PyRun_AnyFile(FILE *fp, const char *name)
2376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002378}
2379
2380#undef PyRun_AnyFileEx
2381PyAPI_FUNC(int)
2382PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002385}
2386
2387#undef PyRun_AnyFileFlags
2388PyAPI_FUNC(int)
2389PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002392}
2393
2394#undef PyRun_File
2395PyAPI_FUNC(PyObject *)
2396PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002399}
2400
2401#undef PyRun_FileEx
2402PyAPI_FUNC(PyObject *)
2403PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002406}
2407
2408#undef PyRun_FileFlags
2409PyAPI_FUNC(PyObject *)
2410PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002414}
2415
2416#undef PyRun_SimpleFile
2417PyAPI_FUNC(int)
2418PyRun_SimpleFile(FILE *f, const char *p)
2419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002421}
2422
2423#undef PyRun_SimpleFileEx
2424PyAPI_FUNC(int)
2425PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002428}
2429
2430
2431#undef PyRun_String
2432PyAPI_FUNC(PyObject *)
2433PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002436}
2437
2438#undef PyRun_SimpleString
2439PyAPI_FUNC(int)
2440PyRun_SimpleString(const char *s)
2441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002443}
2444
2445#undef Py_CompileString
2446PyAPI_FUNC(PyObject *)
2447Py_CompileString(const char *str, const char *p, int s)
2448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002450}
2451
2452#undef PyRun_InteractiveOne
2453PyAPI_FUNC(int)
2454PyRun_InteractiveOne(FILE *f, const char *p)
2455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002457}
2458
2459#undef PyRun_InteractiveLoop
2460PyAPI_FUNC(int)
2461PyRun_InteractiveLoop(FILE *f, const char *p)
2462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002464}
2465
2466#ifdef __cplusplus
2467}
2468#endif