blob: a888a19f2012eb7aad41e16fc6be61d4817089c5 [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");
258 _PyImport_FixupExtension(bimod, "builtins", "builtins");
259 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);
274 _PyImport_FixupExtension(sysmod, "sys", "sys");
275 PySys_SetPath(Py_GetPath());
276 PyDict_SetItemString(interp->sysdict, "modules",
277 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 /* Set up a preliminary stderr printer until we have enough
280 infrastructure for the io module in place. */
281 pstderr = PyFile_NewStdPrinter(fileno(stderr));
282 if (pstderr == NULL)
283 Py_FatalError("Py_Initialize: can't set preliminary stderr");
284 PySys_SetObject("stderr", pstderr);
285 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000290
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000291 /* Initialize _warnings. */
292 _PyWarnings_Init();
293
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000294 _PyTime_Init();
295
Victor Stinnerb744ba12010-05-15 12:27:16 +0000296 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (install_sigs)
299 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 /* Initialize warnings. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 if (PySys_HasWarnOptions()) {
303 PyObject *warnings_module = PyImport_ImportModule("warnings");
304 if (!warnings_module)
305 PyErr_Clear();
306 Py_XDECREF(warnings_module);
307 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 initmain(); /* Module __main__ */
310 if (initstdio() < 0)
311 Py_FatalError(
312 "Py_Initialize: can't initialize sys standard streams");
313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (!Py_NoSiteFlag)
315 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000316}
317
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000318void
319Py_Initialize(void)
320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000322}
323
324
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000325#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000326extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000327#endif
328
Guido van Rossume8432ac2007-07-09 15:04:50 +0000329/* Flush stdout and stderr */
330
Neal Norwitz2bad9702007-08-27 06:19:22 +0000331static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000332flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 PyObject *fout = PySys_GetObject("stdout");
335 PyObject *ferr = PySys_GetObject("stderr");
336 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (fout != NULL && fout != Py_None) {
339 tmp = PyObject_CallMethod(fout, "flush", "");
340 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000341 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 else
343 Py_DECREF(tmp);
344 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000345
Victor Stinner9467b212010-05-14 00:59:09 +0000346 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 tmp = PyObject_CallMethod(ferr, "flush", "");
348 if (tmp == NULL)
349 PyErr_Clear();
350 else
351 Py_DECREF(tmp);
352 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000353}
354
Guido van Rossum25ce5661997-08-02 03:10:38 +0000355/* Undo the effect of Py_Initialize().
356
357 Beware: if multiple interpreter and/or thread states exist, these
358 are not wiped out; only the current thread and interpreter state
359 are deleted. But since everything else is deleted, those other
360 interpreter and thread states should no longer be used.
361
362 (XXX We should do better, e.g. wipe out all interpreters and
363 threads.)
364
365 Locking: as above.
366
367*/
368
369void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000370Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 PyInterpreterState *interp;
373 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (!initialized)
376 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 /* The interpreter is still entirely intact at this point, and the
381 * exit funcs may be relying on that. In particular, if some thread
382 * or exit func is still waiting to do an import, the import machinery
383 * expects Py_IsInitialized() to return true. So don't say the
384 * interpreter is uninitialized until after the exit funcs have run.
385 * Note that Threading.py uses an exit func to do a join on all the
386 * threads created thru it, so this also protects pending imports in
387 * the threads created via Threading.
388 */
389 call_py_exitfuncs();
390 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 /* Flush stdout+stderr */
393 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Get current thread state and interpreter pointer */
396 tstate = PyThreadState_GET();
397 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 /* Disable signal handling */
400 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 /* Clear type lookup cache */
403 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 /* Collect garbage. This may call finalizers; it's nice to call these
406 * before all modules are destroyed.
407 * XXX If a __del__ or weakref callback is triggered here, and tries to
408 * XXX import a module, bad things can happen, because Python no
409 * XXX longer believes it's initialized.
410 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
411 * XXX is easy to provoke that way. I've also seen, e.g.,
412 * XXX Exception exceptions.ImportError: 'No module named sha'
413 * XXX in <function callback at 0x008F5718> ignored
414 * XXX but I'm unclear on exactly how that one happens. In any case,
415 * XXX I haven't seen a real-life report of either of these.
416 */
417 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000418#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 /* With COUNT_ALLOCS, it helps to run GC multiple times:
420 each collection might release some types from the type
421 list, so they become garbage. */
422 while (PyGC_Collect() > 0)
423 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000424#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000425 /* We run this while most interpreter state is still alive, so that
426 debug information can be printed out */
427 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Destroy all modules */
430 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 /* Flush stdout+stderr (again, in case more was printed) */
433 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* Collect final garbage. This disposes of cycles created by
436 * new-style class definitions, for example.
437 * XXX This is disabled because it caused too many problems. If
438 * XXX a __del__ or weakref callback triggers here, Python code has
439 * XXX a hard time running, because even the sys module has been
440 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
441 * XXX One symptom is a sequence of information-free messages
442 * XXX coming from threads (if a __del__ or callback is invoked,
443 * XXX other threads can execute too, and any exception they encounter
444 * XXX triggers a comedy of errors as subsystem after subsystem
445 * XXX fails to find what it *expects* to find in sys to help report
446 * XXX the exception and consequent unexpected failures). I've also
447 * XXX seen segfaults then, after adding print statements to the
448 * XXX Python code getting called.
449 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000450#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000452#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
455 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000458#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000460#endif
461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000463
Tim Peters9cf25ce2003-04-17 15:21:01 +0000464#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* Display all objects still alive -- this can invoke arbitrary
466 * __repr__ overrides, so requires a mostly-intact interpreter.
467 * Alas, a lot of stuff may still be alive now that will be cleaned
468 * up later.
469 */
470 if (Py_GETENV("PYTHONDUMPREFS"))
471 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000472#endif /* Py_TRACE_REFS */
473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* Clear interpreter state */
475 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 /* Now we decref the exception classes. After this point nothing
478 can raise an exception. That's okay, because each Fini() method
479 below has been checked to make sure no exceptions are ever
480 raised.
481 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000486#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000488#endif /* WITH_THREAD */
489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* Delete current thread */
491 PyThreadState_Swap(NULL);
492 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* Sundry finalizers */
495 PyMethod_Fini();
496 PyFrame_Fini();
497 PyCFunction_Fini();
498 PyTuple_Fini();
499 PyList_Fini();
500 PySet_Fini();
501 PyBytes_Fini();
502 PyByteArray_Fini();
503 PyLong_Fini();
504 PyFloat_Fini();
505 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Cleanup Unicode implementation */
508 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000511 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 free((char*)Py_FileSystemDefaultEncoding);
513 Py_FileSystemDefaultEncoding = NULL;
514 }
Christian Heimesc8967002007-11-30 10:18:26 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* XXX Still allocated:
517 - various static ad-hoc pointers to interned strings
518 - int and float free list blocks
519 - whatever various modules and libraries allocate
520 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000523
Tim Peters269b2a62003-04-17 19:52:29 +0000524#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Display addresses (& refcnts) of all objects still alive.
526 * An address can be used to find the repr of the object, printed
527 * above by _Py_PrintReferences.
528 */
529 if (Py_GETENV("PYTHONDUMPREFS"))
530 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000531#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000532#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (Py_GETENV("PYTHONMALLOCSTATS"))
534 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000535#endif
536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538}
539
540/* Create and initialize a new interpreter and thread, and return the
541 new thread. This requires that Py_Initialize() has been called
542 first.
543
544 Unsuccessful initialization yields a NULL pointer. Note that *no*
545 exception information is available even in this case -- the
546 exception information is held in the thread, and there is no
547 thread.
548
549 Locking: as above.
550
551*/
552
553PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000554Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyInterpreterState *interp;
557 PyThreadState *tstate, *save_tstate;
558 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (!initialized)
561 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 interp = PyInterpreterState_New();
564 if (interp == NULL)
565 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 tstate = PyThreadState_New(interp);
568 if (tstate == NULL) {
569 PyInterpreterState_Delete(interp);
570 return NULL;
571 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 interp->modules = PyDict_New();
578 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 bimod = _PyImport_FindExtension("builtins", "builtins");
581 if (bimod != NULL) {
582 interp->builtins = PyModule_GetDict(bimod);
583 if (interp->builtins == NULL)
584 goto handle_error;
585 Py_INCREF(interp->builtins);
586 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* initialize builtin exceptions */
589 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 sysmod = _PyImport_FindExtension("sys", "sys");
592 if (bimod != NULL && sysmod != NULL) {
593 PyObject *pstderr;
594 interp->sysdict = PyModule_GetDict(sysmod);
595 if (interp->sysdict == NULL)
596 goto handle_error;
597 Py_INCREF(interp->sysdict);
598 PySys_SetPath(Py_GetPath());
599 PyDict_SetItemString(interp->sysdict, "modules",
600 interp->modules);
601 /* Set up a preliminary stderr printer until we have enough
602 infrastructure for the io module in place. */
603 pstderr = PyFile_NewStdPrinter(fileno(stderr));
604 if (pstderr == NULL)
605 Py_FatalError("Py_Initialize: can't set preliminary stderr");
606 PySys_SetObject("stderr", pstderr);
607 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 _PyImportHooks_Init();
610 if (initstdio() < 0)
611 Py_FatalError(
612 "Py_Initialize: can't initialize sys standard streams");
613 initmain();
614 if (!Py_NoSiteFlag)
615 initsite();
616 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (!PyErr_Occurred())
619 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000620
Thomas Wouters89f507f2006-12-13 04:49:30 +0000621handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 PyErr_Print();
625 PyThreadState_Clear(tstate);
626 PyThreadState_Swap(save_tstate);
627 PyThreadState_Delete(tstate);
628 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631}
632
633/* Delete an interpreter and its last thread. This requires that the
634 given thread state is current, that the thread has no remaining
635 frames, and that it is its interpreter's only remaining thread.
636 It is a fatal error to violate these constraints.
637
638 (Py_Finalize() doesn't have these constraints -- it zaps
639 everything, regardless.)
640
641 Locking: as above.
642
643*/
644
645void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000646Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (tstate != PyThreadState_GET())
651 Py_FatalError("Py_EndInterpreter: thread is not current");
652 if (tstate->frame != NULL)
653 Py_FatalError("Py_EndInterpreter: thread still has a frame");
654 if (tstate != interp->tstate_head || tstate->next != NULL)
655 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyImport_Cleanup();
658 PyInterpreterState_Clear(interp);
659 PyThreadState_Swap(NULL);
660 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000661}
662
Martin v. Löwis790465f2008-04-05 20:41:37 +0000663static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000664
665void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000666Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (pn && *pn)
669 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000670}
671
Martin v. Löwis790465f2008-04-05 20:41:37 +0000672wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000673Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000676}
677
Martin v. Löwis790465f2008-04-05 20:41:37 +0000678static wchar_t *default_home = NULL;
679static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000680
681void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000682Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000685}
686
Martin v. Löwis790465f2008-04-05 20:41:37 +0000687wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000688Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 wchar_t *home = default_home;
691 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
692 char* chome = Py_GETENV("PYTHONHOME");
693 if (chome) {
694 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
695 if (r != (size_t)-1 && r <= PATH_MAX)
696 home = env_home;
697 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 }
700 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000701}
702
Guido van Rossum6135a871995-01-09 17:53:26 +0000703/* Create __main__ module */
704
705static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000706initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 PyObject *m, *d;
709 m = PyImport_AddModule("__main__");
710 if (m == NULL)
711 Py_FatalError("can't create __main__ module");
712 d = PyModule_GetDict(m);
713 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
714 PyObject *bimod = PyImport_ImportModule("builtins");
715 if (bimod == NULL ||
716 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
717 Py_FatalError("can't add __builtins__ to __main__");
718 Py_DECREF(bimod);
719 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000720}
721
Victor Stinnerc39211f2010-09-29 16:35:47 +0000722/* Redecode a filename from the default filesystem encoding (utf-8) to
723 'new_encoding' encoding with 'errors' error handler */
724static PyObject*
725redecode_filename(PyObject *file, const char *new_encoding,
726 const char *errors)
727{
728 PyObject *file_bytes = NULL, *new_file = NULL;
729
730 file_bytes = PyUnicode_EncodeFSDefault(file);
731 if (file_bytes == NULL)
732 return NULL;
733 new_file = PyUnicode_Decode(
734 PyBytes_AsString(file_bytes),
735 PyBytes_GET_SIZE(file_bytes),
736 new_encoding,
737 errors);
738 Py_DECREF(file_bytes);
739 return new_file;
740}
741
742/* Redecode a path list */
743static int
744redecode_path_list(PyObject *paths,
745 const char *new_encoding, const char *errors)
746{
747 PyObject *filename, *new_filename;
748 Py_ssize_t i, size;
749
750 size = PyList_Size(paths);
751 for (i=0; i < size; i++) {
752 filename = PyList_GetItem(paths, i);
753 if (filename == NULL)
754 return -1;
755
756 new_filename = redecode_filename(filename, new_encoding, errors);
757 if (new_filename == NULL)
758 return -1;
759 if (PyList_SetItem(paths, i, new_filename)) {
760 Py_DECREF(new_filename);
761 return -1;
762 }
763 }
764 return 0;
765}
766
767/* Redecode __file__ and __path__ attributes of sys.modules */
768static int
769redecode_sys_modules(const char *new_encoding, const char *errors)
770{
771 PyInterpreterState *interp;
772 PyObject *modules, *values, *file, *new_file, *paths;
773 PyObject *iter = NULL, *module = NULL;
774
775 interp = PyThreadState_GET()->interp;
776 modules = interp->modules;
777
778 values = PyObject_CallMethod(modules, "values", "");
779 if (values == NULL)
780 goto error;
781
782 iter = PyObject_GetIter(values);
783 Py_DECREF(values);
784 if (iter == NULL)
785 goto error;
786
787 while (1)
788 {
789 module = PyIter_Next(iter);
790 if (module == NULL) {
791 if (PyErr_Occurred())
792 goto error;
793 else
794 break;
795 }
796
797 file = PyModule_GetFilenameObject(module);
798 if (file != NULL) {
799 new_file = redecode_filename(file, new_encoding, errors);
800 Py_DECREF(file);
801 if (new_file == NULL)
802 goto error;
803 if (PyObject_SetAttrString(module, "__file__", new_file)) {
804 Py_DECREF(new_file);
805 goto error;
806 }
807 Py_DECREF(new_file);
808 }
809 else
810 PyErr_Clear();
811
812 paths = PyObject_GetAttrString(module, "__path__");
813 if (paths != NULL) {
814 if (redecode_path_list(paths, new_encoding, errors))
815 goto error;
816 }
817 else
818 PyErr_Clear();
819
820 Py_CLEAR(module);
821 }
822 Py_CLEAR(iter);
823 return 0;
824
825error:
826 Py_XDECREF(iter);
827 Py_XDECREF(module);
828 return -1;
829}
830
831/* Redecode sys.path_importer_cache keys */
832static int
833redecode_sys_path_importer_cache(const char *new_encoding, const char *errors)
834{
835 PyObject *path_importer_cache, *items, *item, *path, *importer, *new_path;
836 PyObject *new_cache = NULL, *iter = NULL;
837
838 path_importer_cache = PySys_GetObject("path_importer_cache");
839 if (path_importer_cache == NULL)
840 goto error;
841
842 items = PyObject_CallMethod(path_importer_cache, "items", "");
843 if (items == NULL)
844 goto error;
845
846 iter = PyObject_GetIter(items);
847 Py_DECREF(items);
848 if (iter == NULL)
849 goto error;
850
851 new_cache = PyDict_New();
852 if (new_cache == NULL)
853 goto error;
854
855 while (1)
856 {
857 item = PyIter_Next(iter);
858 if (item == NULL) {
859 if (PyErr_Occurred())
860 goto error;
861 else
862 break;
863 }
864 path = PyTuple_GET_ITEM(item, 0);
865 importer = PyTuple_GET_ITEM(item, 1);
866
867 new_path = redecode_filename(path, new_encoding, errors);
868 if (new_path == NULL)
869 goto error;
870 if (PyDict_SetItem(new_cache, new_path, importer)) {
871 Py_DECREF(new_path);
872 goto error;
873 }
874 Py_DECREF(new_path);
875 }
876 Py_CLEAR(iter);
877 if (PySys_SetObject("path_importer_cache", new_cache))
878 goto error;
879 Py_CLEAR(new_cache);
880 return 0;
881
882error:
883 Py_XDECREF(iter);
884 Py_XDECREF(new_cache);
885 return -1;
886}
887
888/* Redecode co_filename attribute of all code objects */
889static int
890redecode_code_objects(const char *new_encoding, const char *errors)
891{
892 Py_ssize_t i, len;
893 PyCodeObject *co;
894 PyObject *ref, *new_file;
895
896 len = Py_SIZE(_Py_code_object_list);
897 for (i=0; i < len; i++) {
898 ref = PyList_GET_ITEM(_Py_code_object_list, i);
899 co = (PyCodeObject *)PyWeakref_GetObject(ref);
900 if ((PyObject*)co == Py_None)
901 continue;
902 if (co == NULL)
903 return -1;
904
905 new_file = redecode_filename(co->co_filename, new_encoding, errors);
906 if (new_file == NULL)
907 return -1;
908 Py_DECREF(co->co_filename);
909 co->co_filename = new_file;
910 }
911 Py_CLEAR(_Py_code_object_list);
912 return 0;
913}
914
915/* Redecode the filenames of all modules (__file__ and __path__ attributes),
916 all code objects (co_filename attribute), sys.path, sys.meta_path,
917 sys.executable and sys.path_importer_cache (keys) when the filesystem
918 encoding changes from the default encoding (utf-8) to new_encoding */
919static int
920redecode_filenames(const char *new_encoding)
921{
922 char *errors;
923 PyObject *paths, *executable, *new_executable;
924
925 /* PyUnicode_DecodeFSDefault() and PyUnicode_EncodeFSDefault() do already
926 use utf-8 if Py_FileSystemDefaultEncoding is NULL */
927 if (strcmp(new_encoding, "utf-8") == 0)
928 return 0;
929
930 if (strcmp(new_encoding, "mbcs") != 0)
931 errors = "surrogateescape";
932 else
933 errors = NULL;
934
935 /* sys.modules */
936 if (redecode_sys_modules(new_encoding, errors))
937 return -1;
938
939 /* sys.path and sys.meta_path */
940 paths = PySys_GetObject("path");
941 if (paths != NULL) {
942 if (redecode_path_list(paths, new_encoding, errors))
943 return -1;
944 }
945 paths = PySys_GetObject("meta_path");
946 if (paths != NULL) {
947 if (redecode_path_list(paths, new_encoding, errors))
948 return -1;
949 }
950
951 /* sys.executable */
952 executable = PySys_GetObject("executable");
953 if (executable == NULL)
954 return -1;
955 new_executable = redecode_filename(executable, new_encoding, errors);
956 if (new_executable == NULL)
957 return -1;
958 if (PySys_SetObject("executable", new_executable)) {
959 Py_DECREF(new_executable);
960 return -1;
961 }
962 Py_DECREF(new_executable);
963
964 /* sys.path_importer_cache */
965 if (redecode_sys_path_importer_cache(new_encoding, errors))
966 return -1;
967
968 /* code objects */
969 if (redecode_code_objects(new_encoding, errors))
970 return -1;
971
972 return 0;
973}
974
Victor Stinnerb744ba12010-05-15 12:27:16 +0000975static void
976initfsencoding(void)
977{
978 PyObject *codec;
979#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000980 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000981
Victor Stinner7f84ab52010-06-11 00:36:33 +0000982 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner94908bb2010-08-18 21:23:25 +0000983 const char *env_encoding = Py_GETENV("PYTHONFSENCODING");
984 if (env_encoding != NULL) {
985 codeset = get_codec_name(env_encoding);
986 if (!codeset) {
987 fprintf(stderr, "PYTHONFSENCODING is not a valid encoding:\n");
988 PyErr_Print();
989 }
990 }
991 if (!codeset) {
992 /* On Unix, set the file system encoding according to the
993 user's preference, if the CODESET names a well-known
994 Python codec, and Py_FileSystemDefaultEncoding isn't
995 initialized by other means. Also set the encoding of
996 stdin and stdout if these are terminals. */
997 codeset = get_codeset();
998 }
Victor Stinner7f84ab52010-06-11 00:36:33 +0000999 if (codeset != NULL) {
Victor Stinnerc39211f2010-09-29 16:35:47 +00001000 if (redecode_filenames(codeset))
1001 Py_FatalError("Py_Initialize: can't redecode filenames");
Victor Stinner7f84ab52010-06-11 00:36:33 +00001002 Py_FileSystemDefaultEncoding = codeset;
1003 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinnerc39211f2010-09-29 16:35:47 +00001004 Py_CLEAR(_Py_code_object_list);
Victor Stinner7f84ab52010-06-11 00:36:33 +00001005 return;
Victor Stinner94908bb2010-08-18 21:23:25 +00001006 } else {
1007 fprintf(stderr, "Unable to get the locale encoding:\n");
1008 PyErr_Print();
Victor Stinner7f84ab52010-06-11 00:36:33 +00001009 }
Victor Stinnerb744ba12010-05-15 12:27:16 +00001010
Victor Stinner94908bb2010-08-18 21:23:25 +00001011 fprintf(stderr, "Unable to get the filesystem encoding: fallback to utf-8\n");
Victor Stinner7f84ab52010-06-11 00:36:33 +00001012 Py_FileSystemDefaultEncoding = "utf-8";
1013 Py_HasFileSystemDefaultEncoding = 1;
1014 }
Victor Stinnerb744ba12010-05-15 12:27:16 +00001015#endif
1016
Victor Stinnerc39211f2010-09-29 16:35:47 +00001017 Py_CLEAR(_Py_code_object_list);
1018
Victor Stinnerb744ba12010-05-15 12:27:16 +00001019 /* the encoding is mbcs, utf-8 or ascii */
1020 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1021 if (!codec) {
1022 /* Such error can only occurs in critical situations: no more
1023 * memory, import a module of the standard library failed,
1024 * etc. */
1025 Py_FatalError("Py_Initialize: unable to load the file system codec");
1026 } else {
1027 Py_DECREF(codec);
1028 }
1029}
1030
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001031/* Import the site module (not into __main__ though) */
1032
1033static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001034initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyObject *m;
1037 m = PyImport_ImportModule("site");
1038 if (m == NULL) {
1039 PyErr_Print();
1040 Py_Finalize();
1041 exit(1);
1042 }
1043 else {
1044 Py_DECREF(m);
1045 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001046}
1047
Antoine Pitrou05608432009-01-09 18:53:14 +00001048static PyObject*
1049create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 int fd, int write_mode, char* name,
1051 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +00001052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1054 const char* mode;
1055 PyObject *line_buffering;
1056 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 /* stdin is always opened in buffered mode, first because it shouldn't
1059 make a difference in common use cases, second because TextIOWrapper
1060 depends on the presence of a read1() method which only exists on
1061 buffered streams.
1062 */
1063 if (Py_UnbufferedStdioFlag && write_mode)
1064 buffering = 0;
1065 else
1066 buffering = -1;
1067 if (write_mode)
1068 mode = "wb";
1069 else
1070 mode = "rb";
1071 buf = PyObject_CallMethod(io, "open", "isiOOOi",
1072 fd, mode, buffering,
1073 Py_None, Py_None, Py_None, 0);
1074 if (buf == NULL)
1075 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 if (buffering) {
1078 raw = PyObject_GetAttrString(buf, "raw");
1079 if (raw == NULL)
1080 goto error;
1081 }
1082 else {
1083 raw = buf;
1084 Py_INCREF(raw);
1085 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 text = PyUnicode_FromString(name);
1088 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
1089 goto error;
1090 res = PyObject_CallMethod(raw, "isatty", "");
1091 if (res == NULL)
1092 goto error;
1093 isatty = PyObject_IsTrue(res);
1094 Py_DECREF(res);
1095 if (isatty == -1)
1096 goto error;
1097 if (isatty || Py_UnbufferedStdioFlag)
1098 line_buffering = Py_True;
1099 else
1100 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 Py_CLEAR(raw);
1103 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
1106 buf, encoding, errors,
1107 "\n", line_buffering);
1108 Py_CLEAR(buf);
1109 if (stream == NULL)
1110 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 if (write_mode)
1113 mode = "w";
1114 else
1115 mode = "r";
1116 text = PyUnicode_FromString(mode);
1117 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
1118 goto error;
1119 Py_CLEAR(text);
1120 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001121
1122error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 Py_XDECREF(buf);
1124 Py_XDECREF(stream);
1125 Py_XDECREF(text);
1126 Py_XDECREF(raw);
1127 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001128}
1129
Georg Brandl1a3284e2007-12-02 09:40:06 +00001130/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001131static int
1132initstdio(void)
1133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 PyObject *iomod = NULL, *wrapper;
1135 PyObject *bimod = NULL;
1136 PyObject *m;
1137 PyObject *std = NULL;
1138 int status = 0, fd;
1139 PyObject * encoding_attr;
1140 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 /* Hack to avoid a nasty recursion issue when Python is invoked
1143 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1144 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1145 goto error;
1146 }
1147 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1150 goto error;
1151 }
1152 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (!(bimod = PyImport_ImportModule("builtins"))) {
1155 goto error;
1156 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (!(iomod = PyImport_ImportModule("io"))) {
1159 goto error;
1160 }
1161 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1162 goto error;
1163 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 /* Set builtins.open */
1166 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1167 goto error;
1168 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 encoding = Py_GETENV("PYTHONIOENCODING");
1171 errors = NULL;
1172 if (encoding) {
1173 encoding = strdup(encoding);
1174 errors = strchr(encoding, ':');
1175 if (errors) {
1176 *errors = '\0';
1177 errors++;
1178 }
1179 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 /* Set sys.stdin */
1182 fd = fileno(stdin);
1183 /* Under some conditions stdin, stdout and stderr may not be connected
1184 * and fileno() may point to an invalid file descriptor. For example
1185 * GUI apps don't have valid standard streams by default.
1186 */
1187 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +00001188#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 std = Py_None;
1190 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +00001191#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +00001193#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 }
1195 else {
1196 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1197 if (std == NULL)
1198 goto error;
1199 } /* if (fd < 0) */
1200 PySys_SetObject("__stdin__", std);
1201 PySys_SetObject("stdin", std);
1202 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /* Set sys.stdout */
1205 fd = fileno(stdout);
1206 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +00001207#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 std = Py_None;
1209 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +00001210#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +00001212#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
1214 else {
1215 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1216 if (std == NULL)
1217 goto error;
1218 } /* if (fd < 0) */
1219 PySys_SetObject("__stdout__", std);
1220 PySys_SetObject("stdout", std);
1221 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001222
Guido van Rossum98297ee2007-11-06 21:34:58 +00001223#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 /* Set sys.stderr, replaces the preliminary stderr */
1225 fd = fileno(stderr);
1226 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +00001227#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 std = Py_None;
1229 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +00001230#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +00001232#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 }
1234 else {
1235 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1236 if (std == NULL)
1237 goto error;
1238 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 /* Same as hack above, pre-import stderr's codec to avoid recursion
1241 when import.c tries to write to stderr in verbose mode. */
1242 encoding_attr = PyObject_GetAttrString(std, "encoding");
1243 if (encoding_attr != NULL) {
1244 const char * encoding;
1245 encoding = _PyUnicode_AsString(encoding_attr);
1246 if (encoding != NULL) {
1247 _PyCodec_Lookup(encoding);
1248 }
1249 }
1250 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 PySys_SetObject("__stderr__", std);
1253 PySys_SetObject("stderr", std);
1254 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001255#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001258 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 status = -1;
1260 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 if (encoding)
1263 free(encoding);
1264 Py_XDECREF(bimod);
1265 Py_XDECREF(iomod);
1266 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001267}
1268
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001269/* Parse input from a file and execute it */
1270
1271int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001272PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (filename == NULL)
1276 filename = "???";
1277 if (Py_FdIsInteractive(fp, filename)) {
1278 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1279 if (closeit)
1280 fclose(fp);
1281 return err;
1282 }
1283 else
1284 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001285}
1286
1287int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001288PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 PyObject *v;
1291 int ret;
1292 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (flags == NULL) {
1295 flags = &local_flags;
1296 local_flags.cf_flags = 0;
1297 }
1298 v = PySys_GetObject("ps1");
1299 if (v == NULL) {
1300 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1301 Py_XDECREF(v);
1302 }
1303 v = PySys_GetObject("ps2");
1304 if (v == NULL) {
1305 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1306 Py_XDECREF(v);
1307 }
1308 for (;;) {
1309 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1310 PRINT_TOTAL_REFS();
1311 if (ret == E_EOF)
1312 return 0;
1313 /*
1314 if (ret == E_NOMEM)
1315 return -1;
1316 */
1317 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001318}
1319
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001320/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001321static int PARSER_FLAGS(PyCompilerFlags *flags)
1322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 int parser_flags = 0;
1324 if (!flags)
1325 return 0;
1326 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1327 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1328 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1329 parser_flags |= PyPARSE_IGNORE_COOKIE;
1330 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1331 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1332 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001333}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001334
Thomas Wouters89f507f2006-12-13 04:49:30 +00001335#if 0
1336/* Keep an example of flags with future keyword support. */
1337#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1339 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1340 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1341 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001342#endif
1343
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001344int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001345PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyObject *m, *d, *v, *w, *oenc = NULL;
1348 mod_ty mod;
1349 PyArena *arena;
1350 char *ps1 = "", *ps2 = "", *enc = NULL;
1351 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 if (fp == stdin) {
1354 /* Fetch encoding from sys.stdin */
1355 v = PySys_GetObject("stdin");
1356 if (v == NULL || v == Py_None)
1357 return -1;
1358 oenc = PyObject_GetAttrString(v, "encoding");
1359 if (!oenc)
1360 return -1;
1361 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001362 if (enc == NULL)
1363 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 }
1365 v = PySys_GetObject("ps1");
1366 if (v != NULL) {
1367 v = PyObject_Str(v);
1368 if (v == NULL)
1369 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001370 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001372 if (ps1 == NULL) {
1373 PyErr_Clear();
1374 ps1 = "";
1375 }
1376 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 }
1378 w = PySys_GetObject("ps2");
1379 if (w != NULL) {
1380 w = PyObject_Str(w);
1381 if (w == NULL)
1382 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001383 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001385 if (ps2 == NULL) {
1386 PyErr_Clear();
1387 ps2 = "";
1388 }
1389 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 }
1391 arena = PyArena_New();
1392 if (arena == NULL) {
1393 Py_XDECREF(v);
1394 Py_XDECREF(w);
1395 Py_XDECREF(oenc);
1396 return -1;
1397 }
1398 mod = PyParser_ASTFromFile(fp, filename, enc,
1399 Py_single_input, ps1, ps2,
1400 flags, &errcode, arena);
1401 Py_XDECREF(v);
1402 Py_XDECREF(w);
1403 Py_XDECREF(oenc);
1404 if (mod == NULL) {
1405 PyArena_Free(arena);
1406 if (errcode == E_EOF) {
1407 PyErr_Clear();
1408 return E_EOF;
1409 }
1410 PyErr_Print();
1411 return -1;
1412 }
1413 m = PyImport_AddModule("__main__");
1414 if (m == NULL) {
1415 PyArena_Free(arena);
1416 return -1;
1417 }
1418 d = PyModule_GetDict(m);
1419 v = run_mod(mod, filename, d, d, flags, arena);
1420 PyArena_Free(arena);
1421 flush_io();
1422 if (v == NULL) {
1423 PyErr_Print();
1424 return -1;
1425 }
1426 Py_DECREF(v);
1427 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001428}
1429
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001430/* Check whether a file maybe a pyc file: Look at the extension,
1431 the file type, and, if we may close it, at the first few bytes. */
1432
1433static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001434maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1437 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 /* Only look into the file if we are allowed to close it, since
1440 it then should also be seekable. */
1441 if (closeit) {
1442 /* Read only two bytes of the magic. If the file was opened in
1443 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1444 be read as they are on disk. */
1445 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1446 unsigned char buf[2];
1447 /* Mess: In case of -x, the stream is NOT at its start now,
1448 and ungetc() was used to push back the first newline,
1449 which makes the current stream position formally undefined,
1450 and a x-platform nightmare.
1451 Unfortunately, we have no direct way to know whether -x
1452 was specified. So we use a terrible hack: if the current
1453 stream position is not 0, we assume -x was specified, and
1454 give up. Bug 132850 on SourceForge spells out the
1455 hopelessness of trying anything else (fseek and ftell
1456 don't work predictably x-platform for text-mode files).
1457 */
1458 int ispyc = 0;
1459 if (ftell(fp) == 0) {
1460 if (fread(buf, 1, 2, fp) == 2 &&
1461 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1462 ispyc = 1;
1463 rewind(fp);
1464 }
1465 return ispyc;
1466 }
1467 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001468}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001469
Guido van Rossum0df002c2000-08-27 19:21:52 +00001470int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001471PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 PyObject *m, *d, *v;
1475 const char *ext;
1476 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 m = PyImport_AddModule("__main__");
1479 if (m == NULL)
1480 return -1;
1481 d = PyModule_GetDict(m);
1482 if (PyDict_GetItemString(d, "__file__") == NULL) {
1483 PyObject *f;
Victor Stinner0fe25a42010-06-17 23:08:50 +00001484 f = PyUnicode_FromString(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (f == NULL)
1486 return -1;
1487 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1488 Py_DECREF(f);
1489 return -1;
1490 }
1491 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1492 return -1;
1493 set_file_name = 1;
1494 Py_DECREF(f);
1495 }
1496 len = strlen(filename);
1497 ext = filename + len - (len > 4 ? 4 : 0);
1498 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1499 /* Try to run a pyc file. First, re-open in binary */
1500 if (closeit)
1501 fclose(fp);
1502 if ((fp = fopen(filename, "rb")) == NULL) {
1503 fprintf(stderr, "python: Can't reopen .pyc file\n");
1504 ret = -1;
1505 goto done;
1506 }
1507 /* Turn on optimization if a .pyo file is given */
1508 if (strcmp(ext, ".pyo") == 0)
1509 Py_OptimizeFlag = 1;
1510 v = run_pyc_file(fp, filename, d, d, flags);
1511 } else {
1512 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1513 closeit, flags);
1514 }
1515 flush_io();
1516 if (v == NULL) {
1517 PyErr_Print();
1518 ret = -1;
1519 goto done;
1520 }
1521 Py_DECREF(v);
1522 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001523 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1525 PyErr_Clear();
1526 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001527}
1528
1529int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001530PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 PyObject *m, *d, *v;
1533 m = PyImport_AddModule("__main__");
1534 if (m == NULL)
1535 return -1;
1536 d = PyModule_GetDict(m);
1537 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1538 if (v == NULL) {
1539 PyErr_Print();
1540 return -1;
1541 }
1542 Py_DECREF(v);
1543 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001544}
1545
Barry Warsaw035574d1997-08-29 22:07:17 +00001546static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001547parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 long hold;
1551 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 /* old style errors */
1554 if (PyTuple_Check(err))
1555 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1556 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 if (! (v = PyObject_GetAttrString(err, "msg")))
1561 goto finally;
1562 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 if (!(v = PyObject_GetAttrString(err, "filename")))
1565 goto finally;
1566 if (v == Py_None)
1567 *filename = NULL;
1568 else if (! (*filename = _PyUnicode_AsString(v)))
1569 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 Py_DECREF(v);
1572 if (!(v = PyObject_GetAttrString(err, "lineno")))
1573 goto finally;
1574 hold = PyLong_AsLong(v);
1575 Py_DECREF(v);
1576 v = NULL;
1577 if (hold < 0 && PyErr_Occurred())
1578 goto finally;
1579 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 if (!(v = PyObject_GetAttrString(err, "offset")))
1582 goto finally;
1583 if (v == Py_None) {
1584 *offset = -1;
1585 Py_DECREF(v);
1586 v = NULL;
1587 } else {
1588 hold = PyLong_AsLong(v);
1589 Py_DECREF(v);
1590 v = NULL;
1591 if (hold < 0 && PyErr_Occurred())
1592 goto finally;
1593 *offset = (int)hold;
1594 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 if (!(v = PyObject_GetAttrString(err, "text")))
1597 goto finally;
1598 if (v == Py_None)
1599 *text = NULL;
1600 else if (!PyUnicode_Check(v) ||
1601 !(*text = _PyUnicode_AsString(v)))
1602 goto finally;
1603 Py_DECREF(v);
1604 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001605
1606finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 Py_XDECREF(v);
1608 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001609}
1610
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001611void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001612PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001615}
1616
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001617static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001618print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 char *nl;
1621 if (offset >= 0) {
1622 if (offset > 0 && offset == (int)strlen(text))
1623 offset--;
1624 for (;;) {
1625 nl = strchr(text, '\n');
1626 if (nl == NULL || nl-text >= offset)
1627 break;
1628 offset -= (int)(nl+1-text);
1629 text = nl+1;
1630 }
1631 while (*text == ' ' || *text == '\t') {
1632 text++;
1633 offset--;
1634 }
1635 }
1636 PyFile_WriteString(" ", f);
1637 PyFile_WriteString(text, f);
1638 if (*text == '\0' || text[strlen(text)-1] != '\n')
1639 PyFile_WriteString("\n", f);
1640 if (offset == -1)
1641 return;
1642 PyFile_WriteString(" ", f);
1643 offset--;
1644 while (offset > 0) {
1645 PyFile_WriteString(" ", f);
1646 offset--;
1647 }
1648 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001649}
1650
Guido van Rossum66e8e862001-03-23 17:54:43 +00001651static void
1652handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 PyObject *exception, *value, *tb;
1655 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 if (Py_InspectFlag)
1658 /* Don't exit if -i flag was given. This flag is set to 0
1659 * when entering interactive mode for inspecting. */
1660 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 PyErr_Fetch(&exception, &value, &tb);
1663 fflush(stdout);
1664 if (value == NULL || value == Py_None)
1665 goto done;
1666 if (PyExceptionInstance_Check(value)) {
1667 /* The error code should be in the `code' attribute. */
1668 PyObject *code = PyObject_GetAttrString(value, "code");
1669 if (code) {
1670 Py_DECREF(value);
1671 value = code;
1672 if (value == Py_None)
1673 goto done;
1674 }
1675 /* If we failed to dig out the 'code' attribute,
1676 just let the else clause below print the error. */
1677 }
1678 if (PyLong_Check(value))
1679 exitcode = (int)PyLong_AsLong(value);
1680 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001681 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001682 if (sys_stderr != NULL && sys_stderr != Py_None) {
1683 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1684 } else {
1685 PyObject_Print(value, stderr, Py_PRINT_RAW);
1686 fflush(stderr);
1687 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PySys_WriteStderr("\n");
1689 exitcode = 1;
1690 }
Tim Peterscf615b52003-04-19 18:47:02 +00001691 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 /* Restore and clear the exception info, in order to properly decref
1693 * the exception, value, and traceback. If we just exit instead,
1694 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1695 * some finalizers from running.
1696 */
1697 PyErr_Restore(exception, value, tb);
1698 PyErr_Clear();
1699 Py_Exit(exitcode);
1700 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001701}
1702
1703void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001704PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1709 handle_system_exit();
1710 }
1711 PyErr_Fetch(&exception, &v, &tb);
1712 if (exception == NULL)
1713 return;
1714 PyErr_NormalizeException(&exception, &v, &tb);
1715 if (tb == NULL) {
1716 tb = Py_None;
1717 Py_INCREF(tb);
1718 }
1719 PyException_SetTraceback(v, tb);
1720 if (exception == NULL)
1721 return;
1722 /* Now we know v != NULL too */
1723 if (set_sys_last_vars) {
1724 PySys_SetObject("last_type", exception);
1725 PySys_SetObject("last_value", v);
1726 PySys_SetObject("last_traceback", tb);
1727 }
1728 hook = PySys_GetObject("excepthook");
1729 if (hook) {
1730 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1731 PyObject *result = PyEval_CallObject(hook, args);
1732 if (result == NULL) {
1733 PyObject *exception2, *v2, *tb2;
1734 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1735 handle_system_exit();
1736 }
1737 PyErr_Fetch(&exception2, &v2, &tb2);
1738 PyErr_NormalizeException(&exception2, &v2, &tb2);
1739 /* It should not be possible for exception2 or v2
1740 to be NULL. However PyErr_Display() can't
1741 tolerate NULLs, so just be safe. */
1742 if (exception2 == NULL) {
1743 exception2 = Py_None;
1744 Py_INCREF(exception2);
1745 }
1746 if (v2 == NULL) {
1747 v2 = Py_None;
1748 Py_INCREF(v2);
1749 }
1750 fflush(stdout);
1751 PySys_WriteStderr("Error in sys.excepthook:\n");
1752 PyErr_Display(exception2, v2, tb2);
1753 PySys_WriteStderr("\nOriginal exception was:\n");
1754 PyErr_Display(exception, v, tb);
1755 Py_DECREF(exception2);
1756 Py_DECREF(v2);
1757 Py_XDECREF(tb2);
1758 }
1759 Py_XDECREF(result);
1760 Py_XDECREF(args);
1761 } else {
1762 PySys_WriteStderr("sys.excepthook is missing\n");
1763 PyErr_Display(exception, v, tb);
1764 }
1765 Py_XDECREF(exception);
1766 Py_XDECREF(v);
1767 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001768}
1769
Benjamin Petersone6528212008-07-15 15:32:09 +00001770static void
1771print_exception(PyObject *f, PyObject *value)
1772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 int err = 0;
1774 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 if (!PyExceptionInstance_Check(value)) {
1777 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1778 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1779 PyFile_WriteString(" found\n", f);
1780 return;
1781 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 Py_INCREF(value);
1784 fflush(stdout);
1785 type = (PyObject *) Py_TYPE(value);
1786 tb = PyException_GetTraceback(value);
1787 if (tb && tb != Py_None)
1788 err = PyTraceBack_Print(tb, f);
1789 if (err == 0 &&
1790 PyObject_HasAttrString(value, "print_file_and_line"))
1791 {
1792 PyObject *message;
1793 const char *filename, *text;
1794 int lineno, offset;
1795 if (!parse_syntax_error(value, &message, &filename,
1796 &lineno, &offset, &text))
1797 PyErr_Clear();
1798 else {
1799 char buf[10];
1800 PyFile_WriteString(" File \"", f);
1801 if (filename == NULL)
1802 PyFile_WriteString("<string>", f);
1803 else
1804 PyFile_WriteString(filename, f);
1805 PyFile_WriteString("\", line ", f);
1806 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1807 PyFile_WriteString(buf, f);
1808 PyFile_WriteString("\n", f);
1809 if (text != NULL)
1810 print_error_text(f, offset, text);
1811 Py_DECREF(value);
1812 value = message;
1813 /* Can't be bothered to check all those
1814 PyFile_WriteString() calls */
1815 if (PyErr_Occurred())
1816 err = -1;
1817 }
1818 }
1819 if (err) {
1820 /* Don't do anything else */
1821 }
1822 else {
1823 PyObject* moduleName;
1824 char* className;
1825 assert(PyExceptionClass_Check(type));
1826 className = PyExceptionClass_Name(type);
1827 if (className != NULL) {
1828 char *dot = strrchr(className, '.');
1829 if (dot != NULL)
1830 className = dot+1;
1831 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 moduleName = PyObject_GetAttrString(type, "__module__");
1834 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1835 {
1836 Py_DECREF(moduleName);
1837 err = PyFile_WriteString("<unknown>", f);
1838 }
1839 else {
1840 char* modstr = _PyUnicode_AsString(moduleName);
1841 if (modstr && strcmp(modstr, "builtins"))
1842 {
1843 err = PyFile_WriteString(modstr, f);
1844 err += PyFile_WriteString(".", f);
1845 }
1846 Py_DECREF(moduleName);
1847 }
1848 if (err == 0) {
1849 if (className == NULL)
1850 err = PyFile_WriteString("<unknown>", f);
1851 else
1852 err = PyFile_WriteString(className, f);
1853 }
1854 }
1855 if (err == 0 && (value != Py_None)) {
1856 PyObject *s = PyObject_Str(value);
1857 /* only print colon if the str() of the
1858 object is not the empty string
1859 */
1860 if (s == NULL)
1861 err = -1;
1862 else if (!PyUnicode_Check(s) ||
1863 PyUnicode_GetSize(s) != 0)
1864 err = PyFile_WriteString(": ", f);
1865 if (err == 0)
1866 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1867 Py_XDECREF(s);
1868 }
1869 /* try to write a newline in any case */
1870 err += PyFile_WriteString("\n", f);
1871 Py_XDECREF(tb);
1872 Py_DECREF(value);
1873 /* If an error happened here, don't show it.
1874 XXX This is wrong, but too many callers rely on this behavior. */
1875 if (err != 0)
1876 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001877}
1878
1879static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 "\nThe above exception was the direct cause "
1881 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001882
1883static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 "\nDuring handling of the above exception, "
1885 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001886
1887static void
1888print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 int err = 0, res;
1891 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 if (seen != NULL) {
1894 /* Exception chaining */
1895 if (PySet_Add(seen, value) == -1)
1896 PyErr_Clear();
1897 else if (PyExceptionInstance_Check(value)) {
1898 cause = PyException_GetCause(value);
1899 context = PyException_GetContext(value);
1900 if (cause) {
1901 res = PySet_Contains(seen, cause);
1902 if (res == -1)
1903 PyErr_Clear();
1904 if (res == 0) {
1905 print_exception_recursive(
1906 f, cause, seen);
1907 err |= PyFile_WriteString(
1908 cause_message, f);
1909 }
1910 }
1911 else if (context) {
1912 res = PySet_Contains(seen, context);
1913 if (res == -1)
1914 PyErr_Clear();
1915 if (res == 0) {
1916 print_exception_recursive(
1917 f, context, seen);
1918 err |= PyFile_WriteString(
1919 context_message, f);
1920 }
1921 }
1922 Py_XDECREF(context);
1923 Py_XDECREF(cause);
1924 }
1925 }
1926 print_exception(f, value);
1927 if (err != 0)
1928 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001929}
1930
Thomas Wouters477c8d52006-05-27 19:21:47 +00001931void
1932PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 PyObject *seen;
1935 PyObject *f = PySys_GetObject("stderr");
1936 if (f == Py_None) {
1937 /* pass */
1938 }
1939 else if (f == NULL) {
1940 _PyObject_Dump(value);
1941 fprintf(stderr, "lost sys.stderr\n");
1942 }
1943 else {
1944 /* We choose to ignore seen being possibly NULL, and report
1945 at least the main exception (it could be a MemoryError).
1946 */
1947 seen = PySet_New(NULL);
1948 if (seen == NULL)
1949 PyErr_Clear();
1950 print_exception_recursive(f, value, seen);
1951 Py_XDECREF(seen);
1952 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001953}
1954
Guido van Rossum82598051997-03-05 00:20:32 +00001955PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001956PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 PyObject *ret = NULL;
1960 mod_ty mod;
1961 PyArena *arena = PyArena_New();
1962 if (arena == NULL)
1963 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1966 if (mod != NULL)
1967 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1968 PyArena_Free(arena);
1969 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001970}
1971
1972PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001973PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 PyObject *ret;
1977 mod_ty mod;
1978 PyArena *arena = PyArena_New();
1979 if (arena == NULL)
1980 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1983 flags, NULL, arena);
1984 if (closeit)
1985 fclose(fp);
1986 if (mod == NULL) {
1987 PyArena_Free(arena);
1988 return NULL;
1989 }
1990 ret = run_mod(mod, filename, globals, locals, flags, arena);
1991 PyArena_Free(arena);
1992 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001993}
1994
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001995static void
1996flush_io(void)
1997{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 PyObject *f, *r;
1999 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 /* Save the current exception */
2002 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 f = PySys_GetObject("stderr");
2005 if (f != NULL) {
2006 r = PyObject_CallMethod(f, "flush", "");
2007 if (r)
2008 Py_DECREF(r);
2009 else
2010 PyErr_Clear();
2011 }
2012 f = PySys_GetObject("stdout");
2013 if (f != NULL) {
2014 r = PyObject_CallMethod(f, "flush", "");
2015 if (r)
2016 Py_DECREF(r);
2017 else
2018 PyErr_Clear();
2019 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002022}
2023
Guido van Rossum82598051997-03-05 00:20:32 +00002024static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 PyCodeObject *co;
2029 PyObject *v;
2030 co = PyAST_Compile(mod, filename, flags, arena);
2031 if (co == NULL)
2032 return NULL;
2033 v = PyEval_EvalCode(co, globals, locals);
2034 Py_DECREF(co);
2035 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002036}
2037
Guido van Rossum82598051997-03-05 00:20:32 +00002038static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002039run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 PyCodeObject *co;
2043 PyObject *v;
2044 long magic;
2045 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 magic = PyMarshal_ReadLongFromFile(fp);
2048 if (magic != PyImport_GetMagicNumber()) {
2049 PyErr_SetString(PyExc_RuntimeError,
2050 "Bad magic number in .pyc file");
2051 return NULL;
2052 }
2053 (void) PyMarshal_ReadLongFromFile(fp);
2054 v = PyMarshal_ReadLastObjectFromFile(fp);
2055 fclose(fp);
2056 if (v == NULL || !PyCode_Check(v)) {
2057 Py_XDECREF(v);
2058 PyErr_SetString(PyExc_RuntimeError,
2059 "Bad code object in .pyc file");
2060 return NULL;
2061 }
2062 co = (PyCodeObject *)v;
2063 v = PyEval_EvalCode(co, globals, locals);
2064 if (v && flags)
2065 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2066 Py_DECREF(co);
2067 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002068}
2069
Guido van Rossum82598051997-03-05 00:20:32 +00002070PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00002071Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 PyCodeObject *co;
2075 mod_ty mod;
2076 PyArena *arena = PyArena_New();
2077 if (arena == NULL)
2078 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
2081 if (mod == NULL) {
2082 PyArena_Free(arena);
2083 return NULL;
2084 }
2085 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2086 PyObject *result = PyAST_mod2obj(mod);
2087 PyArena_Free(arena);
2088 return result;
2089 }
2090 co = PyAST_Compile(mod, filename, flags, arena);
2091 PyArena_Free(arena);
2092 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002093}
2094
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002095struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002096Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 struct symtable *st;
2099 mod_ty mod;
2100 PyCompilerFlags flags;
2101 PyArena *arena = PyArena_New();
2102 if (arena == NULL)
2103 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 flags.cf_flags = 0;
2106 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
2107 if (mod == NULL) {
2108 PyArena_Free(arena);
2109 return NULL;
2110 }
2111 st = PySymtable_Build(mod, filename, 0);
2112 PyArena_Free(arena);
2113 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002114}
2115
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116/* Preferred access to parser is through AST. */
2117mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002118PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 mod_ty mod;
2122 PyCompilerFlags localflags;
2123 perrdetail err;
2124 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
2127 &_PyParser_Grammar, start, &err,
2128 &iflags);
2129 if (flags == NULL) {
2130 localflags.cf_flags = 0;
2131 flags = &localflags;
2132 }
2133 if (n) {
2134 flags->cf_flags |= iflags & PyCF_MASK;
2135 mod = PyAST_FromNode(n, flags, filename, arena);
2136 PyNode_Free(n);
2137 return mod;
2138 }
2139 else {
2140 err_input(&err);
2141 return NULL;
2142 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002143}
2144
2145mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00002146PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 int start, char *ps1,
2148 char *ps2, PyCompilerFlags *flags, int *errcode,
2149 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 mod_ty mod;
2152 PyCompilerFlags localflags;
2153 perrdetail err;
2154 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
2157 &_PyParser_Grammar,
2158 start, ps1, ps2, &err, &iflags);
2159 if (flags == NULL) {
2160 localflags.cf_flags = 0;
2161 flags = &localflags;
2162 }
2163 if (n) {
2164 flags->cf_flags |= iflags & PyCF_MASK;
2165 mod = PyAST_FromNode(n, flags, filename, arena);
2166 PyNode_Free(n);
2167 return mod;
2168 }
2169 else {
2170 err_input(&err);
2171 if (errcode)
2172 *errcode = err.error;
2173 return NULL;
2174 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002175}
2176
Guido van Rossuma110aa61994-08-29 12:50:44 +00002177/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002178
Guido van Rossuma110aa61994-08-29 12:50:44 +00002179node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002180PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 perrdetail err;
2183 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2184 &_PyParser_Grammar,
2185 start, NULL, NULL, &err, flags);
2186 if (n == NULL)
2187 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002190}
2191
Guido van Rossuma110aa61994-08-29 12:50:44 +00002192/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002193
Guido van Rossuma110aa61994-08-29 12:50:44 +00002194node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002195PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 perrdetail err;
2198 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2199 start, &err, flags);
2200 if (n == NULL)
2201 err_input(&err);
2202 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002203}
2204
2205node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002206PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 perrdetail err;
2210 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2211 &_PyParser_Grammar, start, &err, flags);
2212 if (n == NULL)
2213 err_input(&err);
2214 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002215}
2216
2217node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002218PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002221}
2222
Guido van Rossum66ebd912003-04-17 16:02:26 +00002223/* May want to move a more generalized form of this to parsetok.c or
2224 even parser modules. */
2225
2226void
2227PyParser_SetError(perrdetail *err)
2228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002230}
2231
Guido van Rossuma110aa61994-08-29 12:50:44 +00002232/* Set the error appropriate to the given input error code (see errcode.h) */
2233
2234static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002235err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 PyObject *v, *w, *errtype, *errtext;
2238 PyObject *msg_obj = NULL;
2239 char *msg = NULL;
2240 errtype = PyExc_SyntaxError;
2241 switch (err->error) {
2242 case E_ERROR:
2243 return;
2244 case E_SYNTAX:
2245 errtype = PyExc_IndentationError;
2246 if (err->expected == INDENT)
2247 msg = "expected an indented block";
2248 else if (err->token == INDENT)
2249 msg = "unexpected indent";
2250 else if (err->token == DEDENT)
2251 msg = "unexpected unindent";
2252 else {
2253 errtype = PyExc_SyntaxError;
2254 msg = "invalid syntax";
2255 }
2256 break;
2257 case E_TOKEN:
2258 msg = "invalid token";
2259 break;
2260 case E_EOFS:
2261 msg = "EOF while scanning triple-quoted string literal";
2262 break;
2263 case E_EOLS:
2264 msg = "EOL while scanning string literal";
2265 break;
2266 case E_INTR:
2267 if (!PyErr_Occurred())
2268 PyErr_SetNone(PyExc_KeyboardInterrupt);
2269 goto cleanup;
2270 case E_NOMEM:
2271 PyErr_NoMemory();
2272 goto cleanup;
2273 case E_EOF:
2274 msg = "unexpected EOF while parsing";
2275 break;
2276 case E_TABSPACE:
2277 errtype = PyExc_TabError;
2278 msg = "inconsistent use of tabs and spaces in indentation";
2279 break;
2280 case E_OVERFLOW:
2281 msg = "expression too long";
2282 break;
2283 case E_DEDENT:
2284 errtype = PyExc_IndentationError;
2285 msg = "unindent does not match any outer indentation level";
2286 break;
2287 case E_TOODEEP:
2288 errtype = PyExc_IndentationError;
2289 msg = "too many levels of indentation";
2290 break;
2291 case E_DECODE: {
2292 PyObject *type, *value, *tb;
2293 PyErr_Fetch(&type, &value, &tb);
2294 msg = "unknown decode error";
2295 if (value != NULL)
2296 msg_obj = PyObject_Str(value);
2297 Py_XDECREF(type);
2298 Py_XDECREF(value);
2299 Py_XDECREF(tb);
2300 break;
2301 }
2302 case E_LINECONT:
2303 msg = "unexpected character after line continuation character";
2304 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 case E_IDENTIFIER:
2307 msg = "invalid character in identifier";
2308 break;
2309 default:
2310 fprintf(stderr, "error=%d\n", err->error);
2311 msg = "unknown parsing error";
2312 break;
2313 }
2314 /* err->text may not be UTF-8 in case of decoding errors.
2315 Explicitly convert to an object. */
2316 if (!err->text) {
2317 errtext = Py_None;
2318 Py_INCREF(Py_None);
2319 } else {
2320 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2321 "replace");
2322 }
2323 v = Py_BuildValue("(ziiN)", err->filename,
2324 err->lineno, err->offset, errtext);
2325 if (v != NULL) {
2326 if (msg_obj)
2327 w = Py_BuildValue("(OO)", msg_obj, v);
2328 else
2329 w = Py_BuildValue("(sO)", msg, v);
2330 } else
2331 w = NULL;
2332 Py_XDECREF(v);
2333 PyErr_SetObject(errtype, w);
2334 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002335cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 Py_XDECREF(msg_obj);
2337 if (err->text != NULL) {
2338 PyObject_FREE(err->text);
2339 err->text = NULL;
2340 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002341}
2342
2343/* Print fatal error message and abort */
2344
2345void
Tim Peters7c321a82002-07-09 02:57:01 +00002346Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 fprintf(stderr, "Fatal Python error: %s\n", msg);
2349 fflush(stderr); /* it helps in Windows debug build */
2350 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002351 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002353#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 {
2355 size_t len = strlen(msg);
2356 WCHAR* buffer;
2357 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 /* Convert the message to wchar_t. This uses a simple one-to-one
2360 conversion, assuming that the this error message actually uses ASCII
2361 only. If this ceases to be true, we will have to convert. */
2362 buffer = alloca( (len+1) * (sizeof *buffer));
2363 for( i=0; i<=len; ++i)
2364 buffer[i] = msg[i];
2365 OutputDebugStringW(L"Fatal Python error: ");
2366 OutputDebugStringW(buffer);
2367 OutputDebugStringW(L"\n");
2368 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002369#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002371#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002372#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002374}
2375
2376/* Clean up and exit */
2377
Guido van Rossuma110aa61994-08-29 12:50:44 +00002378#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002379#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002380#endif
2381
Collin Winter670e6922007-03-21 02:57:17 +00002382static void (*pyexitfunc)(void) = NULL;
2383/* For the atexit module. */
2384void _Py_PyAtExit(void (*func)(void))
2385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002387}
2388
2389static void
2390call_py_exitfuncs(void)
2391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 if (pyexitfunc == NULL)
2393 return;
Collin Winter670e6922007-03-21 02:57:17 +00002394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 (*pyexitfunc)();
2396 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002397}
2398
Antoine Pitrou011bd622009-10-20 21:52:47 +00002399/* Wait until threading._shutdown completes, provided
2400 the threading module was imported in the first place.
2401 The shutdown routine will wait until all non-daemon
2402 "threading" threads have completed. */
2403static void
2404wait_for_thread_shutdown(void)
2405{
2406#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 PyObject *result;
2408 PyThreadState *tstate = PyThreadState_GET();
2409 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2410 "threading");
2411 if (threading == NULL) {
2412 /* threading not imported */
2413 PyErr_Clear();
2414 return;
2415 }
2416 result = PyObject_CallMethod(threading, "_shutdown", "");
2417 if (result == NULL) {
2418 PyErr_WriteUnraisable(threading);
2419 }
2420 else {
2421 Py_DECREF(result);
2422 }
2423 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002424#endif
2425}
2426
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002427#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002428static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002429static int nexitfuncs = 0;
2430
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002431int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 if (nexitfuncs >= NEXITFUNCS)
2434 return -1;
2435 exitfuncs[nexitfuncs++] = func;
2436 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002437}
2438
Guido van Rossumcc283f51997-08-05 02:22:03 +00002439static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002440call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 while (nexitfuncs > 0)
2443 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 fflush(stdout);
2446 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002447}
2448
2449void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002450Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002455}
2456
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002457static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002458initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002459{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002460#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002462#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002463#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002465#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002466#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002468#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002470}
2471
Guido van Rossum7433b121997-02-14 19:45:36 +00002472
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002473/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2474 *
2475 * All of the code in this function must only use async-signal-safe functions,
2476 * listed at `man 7 signal` or
2477 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2478 */
2479void
2480_Py_RestoreSignals(void)
2481{
2482#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002484#endif
2485#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002487#endif
2488#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002490#endif
2491}
2492
2493
Guido van Rossum7433b121997-02-14 19:45:36 +00002494/*
2495 * The file descriptor fd is considered ``interactive'' if either
2496 * a) isatty(fd) is TRUE, or
2497 * b) the -i flag was given, and the filename associated with
2498 * the descriptor is NULL or "<stdin>" or "???".
2499 */
2500int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002501Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 if (isatty((int)fileno(fp)))
2504 return 1;
2505 if (!Py_InteractiveFlag)
2506 return 0;
2507 return (filename == NULL) ||
2508 (strcmp(filename, "<stdin>") == 0) ||
2509 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002510}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002511
2512
Tim Petersd08e3822003-04-17 15:24:21 +00002513#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002514#if defined(WIN32) && defined(_MSC_VER)
2515
2516/* Stack checking for Microsoft C */
2517
2518#include <malloc.h>
2519#include <excpt.h>
2520
Fred Drakee8de31c2000-08-31 05:38:39 +00002521/*
2522 * Return non-zero when we run out of memory on the stack; zero otherwise.
2523 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002524int
Fred Drake399739f2000-08-31 05:52:44 +00002525PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 __try {
2528 /* alloca throws a stack overflow exception if there's
2529 not enough space left on the stack */
2530 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2531 return 0;
2532 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2533 EXCEPTION_EXECUTE_HANDLER :
2534 EXCEPTION_CONTINUE_SEARCH) {
2535 int errcode = _resetstkoflw();
2536 if (errcode == 0)
2537 {
2538 Py_FatalError("Could not reset the stack!");
2539 }
2540 }
2541 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002542}
2543
2544#endif /* WIN32 && _MSC_VER */
2545
2546/* Alternate implementations can be added here... */
2547
2548#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002549
2550
2551/* Wrappers around sigaction() or signal(). */
2552
2553PyOS_sighandler_t
2554PyOS_getsig(int sig)
2555{
2556#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 struct sigaction context;
2558 if (sigaction(sig, NULL, &context) == -1)
2559 return SIG_ERR;
2560 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002561#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002563/* Special signal handling for the secure CRT in Visual Studio 2005 */
2564#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 switch (sig) {
2566 /* Only these signals are valid */
2567 case SIGINT:
2568 case SIGILL:
2569 case SIGFPE:
2570 case SIGSEGV:
2571 case SIGTERM:
2572 case SIGBREAK:
2573 case SIGABRT:
2574 break;
2575 /* Don't call signal() with other values or it will assert */
2576 default:
2577 return SIG_ERR;
2578 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002579#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 handler = signal(sig, SIG_IGN);
2581 if (handler != SIG_ERR)
2582 signal(sig, handler);
2583 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002584#endif
2585}
2586
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002587/*
2588 * All of the code in this function must only use async-signal-safe functions,
2589 * listed at `man 7 signal` or
2590 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2591 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002592PyOS_sighandler_t
2593PyOS_setsig(int sig, PyOS_sighandler_t handler)
2594{
2595#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 /* Some code in Modules/signalmodule.c depends on sigaction() being
2597 * used here if HAVE_SIGACTION is defined. Fix that if this code
2598 * changes to invalidate that assumption.
2599 */
2600 struct sigaction context, ocontext;
2601 context.sa_handler = handler;
2602 sigemptyset(&context.sa_mask);
2603 context.sa_flags = 0;
2604 if (sigaction(sig, &context, &ocontext) == -1)
2605 return SIG_ERR;
2606 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002607#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 PyOS_sighandler_t oldhandler;
2609 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002610#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002612#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002614#endif
2615}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002616
2617/* Deprecated C API functions still provided for binary compatiblity */
2618
2619#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002620PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002624}
2625
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002626#undef PyParser_SimpleParseString
2627PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002628PyParser_SimpleParseString(const char *str, int start)
2629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002631}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002632
2633#undef PyRun_AnyFile
2634PyAPI_FUNC(int)
2635PyRun_AnyFile(FILE *fp, const char *name)
2636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002638}
2639
2640#undef PyRun_AnyFileEx
2641PyAPI_FUNC(int)
2642PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002645}
2646
2647#undef PyRun_AnyFileFlags
2648PyAPI_FUNC(int)
2649PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002652}
2653
2654#undef PyRun_File
2655PyAPI_FUNC(PyObject *)
2656PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002659}
2660
2661#undef PyRun_FileEx
2662PyAPI_FUNC(PyObject *)
2663PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002666}
2667
2668#undef PyRun_FileFlags
2669PyAPI_FUNC(PyObject *)
2670PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002674}
2675
2676#undef PyRun_SimpleFile
2677PyAPI_FUNC(int)
2678PyRun_SimpleFile(FILE *f, const char *p)
2679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002681}
2682
2683#undef PyRun_SimpleFileEx
2684PyAPI_FUNC(int)
2685PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002688}
2689
2690
2691#undef PyRun_String
2692PyAPI_FUNC(PyObject *)
2693PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002696}
2697
2698#undef PyRun_SimpleString
2699PyAPI_FUNC(int)
2700PyRun_SimpleString(const char *s)
2701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002703}
2704
2705#undef Py_CompileString
2706PyAPI_FUNC(PyObject *)
2707Py_CompileString(const char *str, const char *p, int s)
2708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002709 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002710}
2711
2712#undef PyRun_InteractiveOne
2713PyAPI_FUNC(int)
2714PyRun_InteractiveOne(FILE *f, const char *p)
2715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002717}
2718
2719#undef PyRun_InteractiveLoop
2720PyAPI_FUNC(int)
2721PyRun_InteractiveLoop(FILE *f, const char *p)
2722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002724}
2725
2726#ifdef __cplusplus
2727}
2728#endif