blob: 012c1b85f2346986f196d1e38fa66457473574da [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 Stinner8f6b6b02010-10-13 22:02:27 +0000983 /* On Unix, set the file system encoding according to the
984 user's preference, if the CODESET names a well-known
985 Python codec, and Py_FileSystemDefaultEncoding isn't
986 initialized by other means. Also set the encoding of
987 stdin and stdout if these are terminals. */
988 codeset = get_codeset();
Victor Stinner7f84ab52010-06-11 00:36:33 +0000989 if (codeset != NULL) {
Victor Stinnerc39211f2010-09-29 16:35:47 +0000990 if (redecode_filenames(codeset))
991 Py_FatalError("Py_Initialize: can't redecode filenames");
Victor Stinner7f84ab52010-06-11 00:36:33 +0000992 Py_FileSystemDefaultEncoding = codeset;
993 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinnerc39211f2010-09-29 16:35:47 +0000994 Py_CLEAR(_Py_code_object_list);
Victor Stinner7f84ab52010-06-11 00:36:33 +0000995 return;
Victor Stinner94908bb2010-08-18 21:23:25 +0000996 } else {
997 fprintf(stderr, "Unable to get the locale encoding:\n");
998 PyErr_Print();
Victor Stinner7f84ab52010-06-11 00:36:33 +0000999 }
Victor Stinnerb744ba12010-05-15 12:27:16 +00001000
Victor Stinner94908bb2010-08-18 21:23:25 +00001001 fprintf(stderr, "Unable to get the filesystem encoding: fallback to utf-8\n");
Victor Stinner7f84ab52010-06-11 00:36:33 +00001002 Py_FileSystemDefaultEncoding = "utf-8";
1003 Py_HasFileSystemDefaultEncoding = 1;
1004 }
Victor Stinnerb744ba12010-05-15 12:27:16 +00001005#endif
1006
Victor Stinnerc39211f2010-09-29 16:35:47 +00001007 Py_CLEAR(_Py_code_object_list);
1008
Victor Stinnerb744ba12010-05-15 12:27:16 +00001009 /* the encoding is mbcs, utf-8 or ascii */
1010 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1011 if (!codec) {
1012 /* Such error can only occurs in critical situations: no more
1013 * memory, import a module of the standard library failed,
1014 * etc. */
1015 Py_FatalError("Py_Initialize: unable to load the file system codec");
1016 } else {
1017 Py_DECREF(codec);
1018 }
1019}
1020
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001021/* Import the site module (not into __main__ though) */
1022
1023static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001024initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 PyObject *m;
1027 m = PyImport_ImportModule("site");
1028 if (m == NULL) {
1029 PyErr_Print();
1030 Py_Finalize();
1031 exit(1);
1032 }
1033 else {
1034 Py_DECREF(m);
1035 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +00001036}
1037
Antoine Pitrou05608432009-01-09 18:53:14 +00001038static PyObject*
1039create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 int fd, int write_mode, char* name,
1041 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +00001042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1044 const char* mode;
1045 PyObject *line_buffering;
1046 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 /* stdin is always opened in buffered mode, first because it shouldn't
1049 make a difference in common use cases, second because TextIOWrapper
1050 depends on the presence of a read1() method which only exists on
1051 buffered streams.
1052 */
1053 if (Py_UnbufferedStdioFlag && write_mode)
1054 buffering = 0;
1055 else
1056 buffering = -1;
1057 if (write_mode)
1058 mode = "wb";
1059 else
1060 mode = "rb";
1061 buf = PyObject_CallMethod(io, "open", "isiOOOi",
1062 fd, mode, buffering,
1063 Py_None, Py_None, Py_None, 0);
1064 if (buf == NULL)
1065 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 if (buffering) {
1068 raw = PyObject_GetAttrString(buf, "raw");
1069 if (raw == NULL)
1070 goto error;
1071 }
1072 else {
1073 raw = buf;
1074 Py_INCREF(raw);
1075 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 text = PyUnicode_FromString(name);
1078 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
1079 goto error;
1080 res = PyObject_CallMethod(raw, "isatty", "");
1081 if (res == NULL)
1082 goto error;
1083 isatty = PyObject_IsTrue(res);
1084 Py_DECREF(res);
1085 if (isatty == -1)
1086 goto error;
1087 if (isatty || Py_UnbufferedStdioFlag)
1088 line_buffering = Py_True;
1089 else
1090 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 Py_CLEAR(raw);
1093 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
1096 buf, encoding, errors,
1097 "\n", line_buffering);
1098 Py_CLEAR(buf);
1099 if (stream == NULL)
1100 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (write_mode)
1103 mode = "w";
1104 else
1105 mode = "r";
1106 text = PyUnicode_FromString(mode);
1107 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
1108 goto error;
1109 Py_CLEAR(text);
1110 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001111
1112error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 Py_XDECREF(buf);
1114 Py_XDECREF(stream);
1115 Py_XDECREF(text);
1116 Py_XDECREF(raw);
1117 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001118}
1119
Georg Brandl1a3284e2007-12-02 09:40:06 +00001120/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001121static int
1122initstdio(void)
1123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 PyObject *iomod = NULL, *wrapper;
1125 PyObject *bimod = NULL;
1126 PyObject *m;
1127 PyObject *std = NULL;
1128 int status = 0, fd;
1129 PyObject * encoding_attr;
1130 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 /* Hack to avoid a nasty recursion issue when Python is invoked
1133 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1134 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1135 goto error;
1136 }
1137 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1140 goto error;
1141 }
1142 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 if (!(bimod = PyImport_ImportModule("builtins"))) {
1145 goto error;
1146 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (!(iomod = PyImport_ImportModule("io"))) {
1149 goto error;
1150 }
1151 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1152 goto error;
1153 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 /* Set builtins.open */
1156 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1157 goto error;
1158 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 encoding = Py_GETENV("PYTHONIOENCODING");
1161 errors = NULL;
1162 if (encoding) {
1163 encoding = strdup(encoding);
1164 errors = strchr(encoding, ':');
1165 if (errors) {
1166 *errors = '\0';
1167 errors++;
1168 }
1169 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 /* Set sys.stdin */
1172 fd = fileno(stdin);
1173 /* Under some conditions stdin, stdout and stderr may not be connected
1174 * and fileno() may point to an invalid file descriptor. For example
1175 * GUI apps don't have valid standard streams by default.
1176 */
1177 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +00001178#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 std = Py_None;
1180 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +00001181#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +00001183#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 }
1185 else {
1186 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1187 if (std == NULL)
1188 goto error;
1189 } /* if (fd < 0) */
1190 PySys_SetObject("__stdin__", std);
1191 PySys_SetObject("stdin", std);
1192 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 /* Set sys.stdout */
1195 fd = fileno(stdout);
1196 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +00001197#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 std = Py_None;
1199 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +00001200#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +00001202#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 }
1204 else {
1205 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1206 if (std == NULL)
1207 goto error;
1208 } /* if (fd < 0) */
1209 PySys_SetObject("__stdout__", std);
1210 PySys_SetObject("stdout", std);
1211 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001212
Guido van Rossum98297ee2007-11-06 21:34:58 +00001213#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 /* Set sys.stderr, replaces the preliminary stderr */
1215 fd = fileno(stderr);
1216 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +00001217#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 std = Py_None;
1219 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +00001220#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +00001222#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 }
1224 else {
1225 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1226 if (std == NULL)
1227 goto error;
1228 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 /* Same as hack above, pre-import stderr's codec to avoid recursion
1231 when import.c tries to write to stderr in verbose mode. */
1232 encoding_attr = PyObject_GetAttrString(std, "encoding");
1233 if (encoding_attr != NULL) {
1234 const char * encoding;
1235 encoding = _PyUnicode_AsString(encoding_attr);
1236 if (encoding != NULL) {
1237 _PyCodec_Lookup(encoding);
1238 }
1239 }
1240 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 PySys_SetObject("__stderr__", std);
1243 PySys_SetObject("stderr", std);
1244 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001245#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001248 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 status = -1;
1250 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 if (encoding)
1253 free(encoding);
1254 Py_XDECREF(bimod);
1255 Py_XDECREF(iomod);
1256 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001257}
1258
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001259/* Parse input from a file and execute it */
1260
1261int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001262PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 if (filename == NULL)
1266 filename = "???";
1267 if (Py_FdIsInteractive(fp, filename)) {
1268 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1269 if (closeit)
1270 fclose(fp);
1271 return err;
1272 }
1273 else
1274 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001275}
1276
1277int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001278PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 PyObject *v;
1281 int ret;
1282 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (flags == NULL) {
1285 flags = &local_flags;
1286 local_flags.cf_flags = 0;
1287 }
1288 v = PySys_GetObject("ps1");
1289 if (v == NULL) {
1290 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1291 Py_XDECREF(v);
1292 }
1293 v = PySys_GetObject("ps2");
1294 if (v == NULL) {
1295 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1296 Py_XDECREF(v);
1297 }
1298 for (;;) {
1299 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1300 PRINT_TOTAL_REFS();
1301 if (ret == E_EOF)
1302 return 0;
1303 /*
1304 if (ret == E_NOMEM)
1305 return -1;
1306 */
1307 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001308}
1309
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001310/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001311static int PARSER_FLAGS(PyCompilerFlags *flags)
1312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 int parser_flags = 0;
1314 if (!flags)
1315 return 0;
1316 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1317 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1318 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1319 parser_flags |= PyPARSE_IGNORE_COOKIE;
1320 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1321 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1322 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001323}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001324
Thomas Wouters89f507f2006-12-13 04:49:30 +00001325#if 0
1326/* Keep an example of flags with future keyword support. */
1327#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1329 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1330 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1331 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001332#endif
1333
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001334int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001335PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyObject *m, *d, *v, *w, *oenc = NULL;
1338 mod_ty mod;
1339 PyArena *arena;
1340 char *ps1 = "", *ps2 = "", *enc = NULL;
1341 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 if (fp == stdin) {
1344 /* Fetch encoding from sys.stdin */
1345 v = PySys_GetObject("stdin");
1346 if (v == NULL || v == Py_None)
1347 return -1;
1348 oenc = PyObject_GetAttrString(v, "encoding");
1349 if (!oenc)
1350 return -1;
1351 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001352 if (enc == NULL)
1353 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 }
1355 v = PySys_GetObject("ps1");
1356 if (v != NULL) {
1357 v = PyObject_Str(v);
1358 if (v == NULL)
1359 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001360 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001362 if (ps1 == NULL) {
1363 PyErr_Clear();
1364 ps1 = "";
1365 }
1366 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 }
1368 w = PySys_GetObject("ps2");
1369 if (w != NULL) {
1370 w = PyObject_Str(w);
1371 if (w == NULL)
1372 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001373 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001375 if (ps2 == NULL) {
1376 PyErr_Clear();
1377 ps2 = "";
1378 }
1379 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 }
1381 arena = PyArena_New();
1382 if (arena == NULL) {
1383 Py_XDECREF(v);
1384 Py_XDECREF(w);
1385 Py_XDECREF(oenc);
1386 return -1;
1387 }
1388 mod = PyParser_ASTFromFile(fp, filename, enc,
1389 Py_single_input, ps1, ps2,
1390 flags, &errcode, arena);
1391 Py_XDECREF(v);
1392 Py_XDECREF(w);
1393 Py_XDECREF(oenc);
1394 if (mod == NULL) {
1395 PyArena_Free(arena);
1396 if (errcode == E_EOF) {
1397 PyErr_Clear();
1398 return E_EOF;
1399 }
1400 PyErr_Print();
1401 return -1;
1402 }
1403 m = PyImport_AddModule("__main__");
1404 if (m == NULL) {
1405 PyArena_Free(arena);
1406 return -1;
1407 }
1408 d = PyModule_GetDict(m);
1409 v = run_mod(mod, filename, d, d, flags, arena);
1410 PyArena_Free(arena);
1411 flush_io();
1412 if (v == NULL) {
1413 PyErr_Print();
1414 return -1;
1415 }
1416 Py_DECREF(v);
1417 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001418}
1419
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001420/* Check whether a file maybe a pyc file: Look at the extension,
1421 the file type, and, if we may close it, at the first few bytes. */
1422
1423static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001424maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1427 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 /* Only look into the file if we are allowed to close it, since
1430 it then should also be seekable. */
1431 if (closeit) {
1432 /* Read only two bytes of the magic. If the file was opened in
1433 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1434 be read as they are on disk. */
1435 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1436 unsigned char buf[2];
1437 /* Mess: In case of -x, the stream is NOT at its start now,
1438 and ungetc() was used to push back the first newline,
1439 which makes the current stream position formally undefined,
1440 and a x-platform nightmare.
1441 Unfortunately, we have no direct way to know whether -x
1442 was specified. So we use a terrible hack: if the current
1443 stream position is not 0, we assume -x was specified, and
1444 give up. Bug 132850 on SourceForge spells out the
1445 hopelessness of trying anything else (fseek and ftell
1446 don't work predictably x-platform for text-mode files).
1447 */
1448 int ispyc = 0;
1449 if (ftell(fp) == 0) {
1450 if (fread(buf, 1, 2, fp) == 2 &&
1451 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1452 ispyc = 1;
1453 rewind(fp);
1454 }
1455 return ispyc;
1456 }
1457 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001458}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001459
Guido van Rossum0df002c2000-08-27 19:21:52 +00001460int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001461PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 PyObject *m, *d, *v;
1465 const char *ext;
1466 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 m = PyImport_AddModule("__main__");
1469 if (m == NULL)
1470 return -1;
1471 d = PyModule_GetDict(m);
1472 if (PyDict_GetItemString(d, "__file__") == NULL) {
1473 PyObject *f;
Victor Stinner0fe25a42010-06-17 23:08:50 +00001474 f = PyUnicode_FromString(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 if (f == NULL)
1476 return -1;
1477 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1478 Py_DECREF(f);
1479 return -1;
1480 }
1481 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1482 return -1;
1483 set_file_name = 1;
1484 Py_DECREF(f);
1485 }
1486 len = strlen(filename);
1487 ext = filename + len - (len > 4 ? 4 : 0);
1488 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1489 /* Try to run a pyc file. First, re-open in binary */
1490 if (closeit)
1491 fclose(fp);
1492 if ((fp = fopen(filename, "rb")) == NULL) {
1493 fprintf(stderr, "python: Can't reopen .pyc file\n");
1494 ret = -1;
1495 goto done;
1496 }
1497 /* Turn on optimization if a .pyo file is given */
1498 if (strcmp(ext, ".pyo") == 0)
1499 Py_OptimizeFlag = 1;
1500 v = run_pyc_file(fp, filename, d, d, flags);
1501 } else {
1502 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1503 closeit, flags);
1504 }
1505 flush_io();
1506 if (v == NULL) {
1507 PyErr_Print();
1508 ret = -1;
1509 goto done;
1510 }
1511 Py_DECREF(v);
1512 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001513 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1515 PyErr_Clear();
1516 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001517}
1518
1519int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001520PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 PyObject *m, *d, *v;
1523 m = PyImport_AddModule("__main__");
1524 if (m == NULL)
1525 return -1;
1526 d = PyModule_GetDict(m);
1527 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1528 if (v == NULL) {
1529 PyErr_Print();
1530 return -1;
1531 }
1532 Py_DECREF(v);
1533 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001534}
1535
Barry Warsaw035574d1997-08-29 22:07:17 +00001536static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001537parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 long hold;
1541 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 /* old style errors */
1544 if (PyTuple_Check(err))
1545 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1546 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 if (! (v = PyObject_GetAttrString(err, "msg")))
1551 goto finally;
1552 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 if (!(v = PyObject_GetAttrString(err, "filename")))
1555 goto finally;
1556 if (v == Py_None)
1557 *filename = NULL;
1558 else if (! (*filename = _PyUnicode_AsString(v)))
1559 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 Py_DECREF(v);
1562 if (!(v = PyObject_GetAttrString(err, "lineno")))
1563 goto finally;
1564 hold = PyLong_AsLong(v);
1565 Py_DECREF(v);
1566 v = NULL;
1567 if (hold < 0 && PyErr_Occurred())
1568 goto finally;
1569 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 if (!(v = PyObject_GetAttrString(err, "offset")))
1572 goto finally;
1573 if (v == Py_None) {
1574 *offset = -1;
1575 Py_DECREF(v);
1576 v = NULL;
1577 } else {
1578 hold = PyLong_AsLong(v);
1579 Py_DECREF(v);
1580 v = NULL;
1581 if (hold < 0 && PyErr_Occurred())
1582 goto finally;
1583 *offset = (int)hold;
1584 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (!(v = PyObject_GetAttrString(err, "text")))
1587 goto finally;
1588 if (v == Py_None)
1589 *text = NULL;
1590 else if (!PyUnicode_Check(v) ||
1591 !(*text = _PyUnicode_AsString(v)))
1592 goto finally;
1593 Py_DECREF(v);
1594 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001595
1596finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 Py_XDECREF(v);
1598 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001599}
1600
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001601void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001602PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001605}
1606
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001607static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001608print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 char *nl;
1611 if (offset >= 0) {
1612 if (offset > 0 && offset == (int)strlen(text))
1613 offset--;
1614 for (;;) {
1615 nl = strchr(text, '\n');
1616 if (nl == NULL || nl-text >= offset)
1617 break;
1618 offset -= (int)(nl+1-text);
1619 text = nl+1;
1620 }
1621 while (*text == ' ' || *text == '\t') {
1622 text++;
1623 offset--;
1624 }
1625 }
1626 PyFile_WriteString(" ", f);
1627 PyFile_WriteString(text, f);
1628 if (*text == '\0' || text[strlen(text)-1] != '\n')
1629 PyFile_WriteString("\n", f);
1630 if (offset == -1)
1631 return;
1632 PyFile_WriteString(" ", f);
1633 offset--;
1634 while (offset > 0) {
1635 PyFile_WriteString(" ", f);
1636 offset--;
1637 }
1638 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001639}
1640
Guido van Rossum66e8e862001-03-23 17:54:43 +00001641static void
1642handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 PyObject *exception, *value, *tb;
1645 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 if (Py_InspectFlag)
1648 /* Don't exit if -i flag was given. This flag is set to 0
1649 * when entering interactive mode for inspecting. */
1650 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 PyErr_Fetch(&exception, &value, &tb);
1653 fflush(stdout);
1654 if (value == NULL || value == Py_None)
1655 goto done;
1656 if (PyExceptionInstance_Check(value)) {
1657 /* The error code should be in the `code' attribute. */
1658 PyObject *code = PyObject_GetAttrString(value, "code");
1659 if (code) {
1660 Py_DECREF(value);
1661 value = code;
1662 if (value == Py_None)
1663 goto done;
1664 }
1665 /* If we failed to dig out the 'code' attribute,
1666 just let the else clause below print the error. */
1667 }
1668 if (PyLong_Check(value))
1669 exitcode = (int)PyLong_AsLong(value);
1670 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001671 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001672 if (sys_stderr != NULL && sys_stderr != Py_None) {
1673 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1674 } else {
1675 PyObject_Print(value, stderr, Py_PRINT_RAW);
1676 fflush(stderr);
1677 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 PySys_WriteStderr("\n");
1679 exitcode = 1;
1680 }
Tim Peterscf615b52003-04-19 18:47:02 +00001681 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 /* Restore and clear the exception info, in order to properly decref
1683 * the exception, value, and traceback. If we just exit instead,
1684 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1685 * some finalizers from running.
1686 */
1687 PyErr_Restore(exception, value, tb);
1688 PyErr_Clear();
1689 Py_Exit(exitcode);
1690 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001691}
1692
1693void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001694PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1699 handle_system_exit();
1700 }
1701 PyErr_Fetch(&exception, &v, &tb);
1702 if (exception == NULL)
1703 return;
1704 PyErr_NormalizeException(&exception, &v, &tb);
1705 if (tb == NULL) {
1706 tb = Py_None;
1707 Py_INCREF(tb);
1708 }
1709 PyException_SetTraceback(v, tb);
1710 if (exception == NULL)
1711 return;
1712 /* Now we know v != NULL too */
1713 if (set_sys_last_vars) {
1714 PySys_SetObject("last_type", exception);
1715 PySys_SetObject("last_value", v);
1716 PySys_SetObject("last_traceback", tb);
1717 }
1718 hook = PySys_GetObject("excepthook");
1719 if (hook) {
1720 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1721 PyObject *result = PyEval_CallObject(hook, args);
1722 if (result == NULL) {
1723 PyObject *exception2, *v2, *tb2;
1724 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1725 handle_system_exit();
1726 }
1727 PyErr_Fetch(&exception2, &v2, &tb2);
1728 PyErr_NormalizeException(&exception2, &v2, &tb2);
1729 /* It should not be possible for exception2 or v2
1730 to be NULL. However PyErr_Display() can't
1731 tolerate NULLs, so just be safe. */
1732 if (exception2 == NULL) {
1733 exception2 = Py_None;
1734 Py_INCREF(exception2);
1735 }
1736 if (v2 == NULL) {
1737 v2 = Py_None;
1738 Py_INCREF(v2);
1739 }
1740 fflush(stdout);
1741 PySys_WriteStderr("Error in sys.excepthook:\n");
1742 PyErr_Display(exception2, v2, tb2);
1743 PySys_WriteStderr("\nOriginal exception was:\n");
1744 PyErr_Display(exception, v, tb);
1745 Py_DECREF(exception2);
1746 Py_DECREF(v2);
1747 Py_XDECREF(tb2);
1748 }
1749 Py_XDECREF(result);
1750 Py_XDECREF(args);
1751 } else {
1752 PySys_WriteStderr("sys.excepthook is missing\n");
1753 PyErr_Display(exception, v, tb);
1754 }
1755 Py_XDECREF(exception);
1756 Py_XDECREF(v);
1757 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001758}
1759
Benjamin Petersone6528212008-07-15 15:32:09 +00001760static void
1761print_exception(PyObject *f, PyObject *value)
1762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 int err = 0;
1764 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 if (!PyExceptionInstance_Check(value)) {
1767 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1768 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1769 PyFile_WriteString(" found\n", f);
1770 return;
1771 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 Py_INCREF(value);
1774 fflush(stdout);
1775 type = (PyObject *) Py_TYPE(value);
1776 tb = PyException_GetTraceback(value);
1777 if (tb && tb != Py_None)
1778 err = PyTraceBack_Print(tb, f);
1779 if (err == 0 &&
1780 PyObject_HasAttrString(value, "print_file_and_line"))
1781 {
1782 PyObject *message;
1783 const char *filename, *text;
1784 int lineno, offset;
1785 if (!parse_syntax_error(value, &message, &filename,
1786 &lineno, &offset, &text))
1787 PyErr_Clear();
1788 else {
1789 char buf[10];
1790 PyFile_WriteString(" File \"", f);
1791 if (filename == NULL)
1792 PyFile_WriteString("<string>", f);
1793 else
1794 PyFile_WriteString(filename, f);
1795 PyFile_WriteString("\", line ", f);
1796 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1797 PyFile_WriteString(buf, f);
1798 PyFile_WriteString("\n", f);
1799 if (text != NULL)
1800 print_error_text(f, offset, text);
1801 Py_DECREF(value);
1802 value = message;
1803 /* Can't be bothered to check all those
1804 PyFile_WriteString() calls */
1805 if (PyErr_Occurred())
1806 err = -1;
1807 }
1808 }
1809 if (err) {
1810 /* Don't do anything else */
1811 }
1812 else {
1813 PyObject* moduleName;
1814 char* className;
1815 assert(PyExceptionClass_Check(type));
1816 className = PyExceptionClass_Name(type);
1817 if (className != NULL) {
1818 char *dot = strrchr(className, '.');
1819 if (dot != NULL)
1820 className = dot+1;
1821 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 moduleName = PyObject_GetAttrString(type, "__module__");
1824 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1825 {
1826 Py_DECREF(moduleName);
1827 err = PyFile_WriteString("<unknown>", f);
1828 }
1829 else {
1830 char* modstr = _PyUnicode_AsString(moduleName);
1831 if (modstr && strcmp(modstr, "builtins"))
1832 {
1833 err = PyFile_WriteString(modstr, f);
1834 err += PyFile_WriteString(".", f);
1835 }
1836 Py_DECREF(moduleName);
1837 }
1838 if (err == 0) {
1839 if (className == NULL)
1840 err = PyFile_WriteString("<unknown>", f);
1841 else
1842 err = PyFile_WriteString(className, f);
1843 }
1844 }
1845 if (err == 0 && (value != Py_None)) {
1846 PyObject *s = PyObject_Str(value);
1847 /* only print colon if the str() of the
1848 object is not the empty string
1849 */
1850 if (s == NULL)
1851 err = -1;
1852 else if (!PyUnicode_Check(s) ||
1853 PyUnicode_GetSize(s) != 0)
1854 err = PyFile_WriteString(": ", f);
1855 if (err == 0)
1856 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1857 Py_XDECREF(s);
1858 }
1859 /* try to write a newline in any case */
1860 err += PyFile_WriteString("\n", f);
1861 Py_XDECREF(tb);
1862 Py_DECREF(value);
1863 /* If an error happened here, don't show it.
1864 XXX This is wrong, but too many callers rely on this behavior. */
1865 if (err != 0)
1866 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001867}
1868
1869static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 "\nThe above exception was the direct cause "
1871 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001872
1873static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 "\nDuring handling of the above exception, "
1875 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001876
1877static void
1878print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 int err = 0, res;
1881 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (seen != NULL) {
1884 /* Exception chaining */
1885 if (PySet_Add(seen, value) == -1)
1886 PyErr_Clear();
1887 else if (PyExceptionInstance_Check(value)) {
1888 cause = PyException_GetCause(value);
1889 context = PyException_GetContext(value);
1890 if (cause) {
1891 res = PySet_Contains(seen, cause);
1892 if (res == -1)
1893 PyErr_Clear();
1894 if (res == 0) {
1895 print_exception_recursive(
1896 f, cause, seen);
1897 err |= PyFile_WriteString(
1898 cause_message, f);
1899 }
1900 }
1901 else if (context) {
1902 res = PySet_Contains(seen, context);
1903 if (res == -1)
1904 PyErr_Clear();
1905 if (res == 0) {
1906 print_exception_recursive(
1907 f, context, seen);
1908 err |= PyFile_WriteString(
1909 context_message, f);
1910 }
1911 }
1912 Py_XDECREF(context);
1913 Py_XDECREF(cause);
1914 }
1915 }
1916 print_exception(f, value);
1917 if (err != 0)
1918 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001919}
1920
Thomas Wouters477c8d52006-05-27 19:21:47 +00001921void
1922PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 PyObject *seen;
1925 PyObject *f = PySys_GetObject("stderr");
1926 if (f == Py_None) {
1927 /* pass */
1928 }
1929 else if (f == NULL) {
1930 _PyObject_Dump(value);
1931 fprintf(stderr, "lost sys.stderr\n");
1932 }
1933 else {
1934 /* We choose to ignore seen being possibly NULL, and report
1935 at least the main exception (it could be a MemoryError).
1936 */
1937 seen = PySet_New(NULL);
1938 if (seen == NULL)
1939 PyErr_Clear();
1940 print_exception_recursive(f, value, seen);
1941 Py_XDECREF(seen);
1942 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001943}
1944
Guido van Rossum82598051997-03-05 00:20:32 +00001945PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001946PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 PyObject *ret = NULL;
1950 mod_ty mod;
1951 PyArena *arena = PyArena_New();
1952 if (arena == NULL)
1953 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1956 if (mod != NULL)
1957 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1958 PyArena_Free(arena);
1959 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001960}
1961
1962PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001963PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 PyObject *ret;
1967 mod_ty mod;
1968 PyArena *arena = PyArena_New();
1969 if (arena == NULL)
1970 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1973 flags, NULL, arena);
1974 if (closeit)
1975 fclose(fp);
1976 if (mod == NULL) {
1977 PyArena_Free(arena);
1978 return NULL;
1979 }
1980 ret = run_mod(mod, filename, globals, locals, flags, arena);
1981 PyArena_Free(arena);
1982 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001983}
1984
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001985static void
1986flush_io(void)
1987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 PyObject *f, *r;
1989 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 /* Save the current exception */
1992 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 f = PySys_GetObject("stderr");
1995 if (f != NULL) {
1996 r = PyObject_CallMethod(f, "flush", "");
1997 if (r)
1998 Py_DECREF(r);
1999 else
2000 PyErr_Clear();
2001 }
2002 f = PySys_GetObject("stdout");
2003 if (f != NULL) {
2004 r = PyObject_CallMethod(f, "flush", "");
2005 if (r)
2006 Py_DECREF(r);
2007 else
2008 PyErr_Clear();
2009 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002012}
2013
Guido van Rossum82598051997-03-05 00:20:32 +00002014static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 PyCodeObject *co;
2019 PyObject *v;
2020 co = PyAST_Compile(mod, filename, flags, arena);
2021 if (co == NULL)
2022 return NULL;
2023 v = PyEval_EvalCode(co, globals, locals);
2024 Py_DECREF(co);
2025 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002026}
2027
Guido van Rossum82598051997-03-05 00:20:32 +00002028static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002029run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 PyCodeObject *co;
2033 PyObject *v;
2034 long magic;
2035 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 magic = PyMarshal_ReadLongFromFile(fp);
2038 if (magic != PyImport_GetMagicNumber()) {
2039 PyErr_SetString(PyExc_RuntimeError,
2040 "Bad magic number in .pyc file");
2041 return NULL;
2042 }
2043 (void) PyMarshal_ReadLongFromFile(fp);
2044 v = PyMarshal_ReadLastObjectFromFile(fp);
2045 fclose(fp);
2046 if (v == NULL || !PyCode_Check(v)) {
2047 Py_XDECREF(v);
2048 PyErr_SetString(PyExc_RuntimeError,
2049 "Bad code object in .pyc file");
2050 return NULL;
2051 }
2052 co = (PyCodeObject *)v;
2053 v = PyEval_EvalCode(co, globals, locals);
2054 if (v && flags)
2055 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2056 Py_DECREF(co);
2057 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002058}
2059
Guido van Rossum82598051997-03-05 00:20:32 +00002060PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00002061Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 PyCodeObject *co;
2065 mod_ty mod;
2066 PyArena *arena = PyArena_New();
2067 if (arena == NULL)
2068 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
2071 if (mod == NULL) {
2072 PyArena_Free(arena);
2073 return NULL;
2074 }
2075 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2076 PyObject *result = PyAST_mod2obj(mod);
2077 PyArena_Free(arena);
2078 return result;
2079 }
2080 co = PyAST_Compile(mod, filename, flags, arena);
2081 PyArena_Free(arena);
2082 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002083}
2084
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002085struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002086Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 struct symtable *st;
2089 mod_ty mod;
2090 PyCompilerFlags flags;
2091 PyArena *arena = PyArena_New();
2092 if (arena == NULL)
2093 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 flags.cf_flags = 0;
2096 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
2097 if (mod == NULL) {
2098 PyArena_Free(arena);
2099 return NULL;
2100 }
2101 st = PySymtable_Build(mod, filename, 0);
2102 PyArena_Free(arena);
2103 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002104}
2105
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002106/* Preferred access to parser is through AST. */
2107mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002108PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 mod_ty mod;
2112 PyCompilerFlags localflags;
2113 perrdetail err;
2114 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
2117 &_PyParser_Grammar, start, &err,
2118 &iflags);
2119 if (flags == NULL) {
2120 localflags.cf_flags = 0;
2121 flags = &localflags;
2122 }
2123 if (n) {
2124 flags->cf_flags |= iflags & PyCF_MASK;
2125 mod = PyAST_FromNode(n, flags, filename, arena);
2126 PyNode_Free(n);
2127 return mod;
2128 }
2129 else {
2130 err_input(&err);
2131 return NULL;
2132 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002133}
2134
2135mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00002136PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 int start, char *ps1,
2138 char *ps2, PyCompilerFlags *flags, int *errcode,
2139 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 mod_ty mod;
2142 PyCompilerFlags localflags;
2143 perrdetail err;
2144 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
2147 &_PyParser_Grammar,
2148 start, ps1, ps2, &err, &iflags);
2149 if (flags == NULL) {
2150 localflags.cf_flags = 0;
2151 flags = &localflags;
2152 }
2153 if (n) {
2154 flags->cf_flags |= iflags & PyCF_MASK;
2155 mod = PyAST_FromNode(n, flags, filename, arena);
2156 PyNode_Free(n);
2157 return mod;
2158 }
2159 else {
2160 err_input(&err);
2161 if (errcode)
2162 *errcode = err.error;
2163 return NULL;
2164 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002165}
2166
Guido van Rossuma110aa61994-08-29 12:50:44 +00002167/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002168
Guido van Rossuma110aa61994-08-29 12:50:44 +00002169node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002170PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 perrdetail err;
2173 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2174 &_PyParser_Grammar,
2175 start, NULL, NULL, &err, flags);
2176 if (n == NULL)
2177 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002180}
2181
Guido van Rossuma110aa61994-08-29 12:50:44 +00002182/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002183
Guido van Rossuma110aa61994-08-29 12:50:44 +00002184node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002185PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 perrdetail err;
2188 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2189 start, &err, flags);
2190 if (n == NULL)
2191 err_input(&err);
2192 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002193}
2194
2195node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002196PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 perrdetail err;
2200 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2201 &_PyParser_Grammar, start, &err, flags);
2202 if (n == NULL)
2203 err_input(&err);
2204 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002205}
2206
2207node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002208PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002211}
2212
Guido van Rossum66ebd912003-04-17 16:02:26 +00002213/* May want to move a more generalized form of this to parsetok.c or
2214 even parser modules. */
2215
2216void
2217PyParser_SetError(perrdetail *err)
2218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002220}
2221
Guido van Rossuma110aa61994-08-29 12:50:44 +00002222/* Set the error appropriate to the given input error code (see errcode.h) */
2223
2224static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002225err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 PyObject *v, *w, *errtype, *errtext;
2228 PyObject *msg_obj = NULL;
2229 char *msg = NULL;
2230 errtype = PyExc_SyntaxError;
2231 switch (err->error) {
2232 case E_ERROR:
2233 return;
2234 case E_SYNTAX:
2235 errtype = PyExc_IndentationError;
2236 if (err->expected == INDENT)
2237 msg = "expected an indented block";
2238 else if (err->token == INDENT)
2239 msg = "unexpected indent";
2240 else if (err->token == DEDENT)
2241 msg = "unexpected unindent";
2242 else {
2243 errtype = PyExc_SyntaxError;
2244 msg = "invalid syntax";
2245 }
2246 break;
2247 case E_TOKEN:
2248 msg = "invalid token";
2249 break;
2250 case E_EOFS:
2251 msg = "EOF while scanning triple-quoted string literal";
2252 break;
2253 case E_EOLS:
2254 msg = "EOL while scanning string literal";
2255 break;
2256 case E_INTR:
2257 if (!PyErr_Occurred())
2258 PyErr_SetNone(PyExc_KeyboardInterrupt);
2259 goto cleanup;
2260 case E_NOMEM:
2261 PyErr_NoMemory();
2262 goto cleanup;
2263 case E_EOF:
2264 msg = "unexpected EOF while parsing";
2265 break;
2266 case E_TABSPACE:
2267 errtype = PyExc_TabError;
2268 msg = "inconsistent use of tabs and spaces in indentation";
2269 break;
2270 case E_OVERFLOW:
2271 msg = "expression too long";
2272 break;
2273 case E_DEDENT:
2274 errtype = PyExc_IndentationError;
2275 msg = "unindent does not match any outer indentation level";
2276 break;
2277 case E_TOODEEP:
2278 errtype = PyExc_IndentationError;
2279 msg = "too many levels of indentation";
2280 break;
2281 case E_DECODE: {
2282 PyObject *type, *value, *tb;
2283 PyErr_Fetch(&type, &value, &tb);
2284 msg = "unknown decode error";
2285 if (value != NULL)
2286 msg_obj = PyObject_Str(value);
2287 Py_XDECREF(type);
2288 Py_XDECREF(value);
2289 Py_XDECREF(tb);
2290 break;
2291 }
2292 case E_LINECONT:
2293 msg = "unexpected character after line continuation character";
2294 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 case E_IDENTIFIER:
2297 msg = "invalid character in identifier";
2298 break;
2299 default:
2300 fprintf(stderr, "error=%d\n", err->error);
2301 msg = "unknown parsing error";
2302 break;
2303 }
2304 /* err->text may not be UTF-8 in case of decoding errors.
2305 Explicitly convert to an object. */
2306 if (!err->text) {
2307 errtext = Py_None;
2308 Py_INCREF(Py_None);
2309 } else {
2310 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2311 "replace");
2312 }
2313 v = Py_BuildValue("(ziiN)", err->filename,
2314 err->lineno, err->offset, errtext);
2315 if (v != NULL) {
2316 if (msg_obj)
2317 w = Py_BuildValue("(OO)", msg_obj, v);
2318 else
2319 w = Py_BuildValue("(sO)", msg, v);
2320 } else
2321 w = NULL;
2322 Py_XDECREF(v);
2323 PyErr_SetObject(errtype, w);
2324 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002325cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 Py_XDECREF(msg_obj);
2327 if (err->text != NULL) {
2328 PyObject_FREE(err->text);
2329 err->text = NULL;
2330 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002331}
2332
2333/* Print fatal error message and abort */
2334
2335void
Tim Peters7c321a82002-07-09 02:57:01 +00002336Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 fprintf(stderr, "Fatal Python error: %s\n", msg);
2339 fflush(stderr); /* it helps in Windows debug build */
2340 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002341 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002343#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 {
2345 size_t len = strlen(msg);
2346 WCHAR* buffer;
2347 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* Convert the message to wchar_t. This uses a simple one-to-one
2350 conversion, assuming that the this error message actually uses ASCII
2351 only. If this ceases to be true, we will have to convert. */
2352 buffer = alloca( (len+1) * (sizeof *buffer));
2353 for( i=0; i<=len; ++i)
2354 buffer[i] = msg[i];
2355 OutputDebugStringW(L"Fatal Python error: ");
2356 OutputDebugStringW(buffer);
2357 OutputDebugStringW(L"\n");
2358 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002359#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002361#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002362#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002364}
2365
2366/* Clean up and exit */
2367
Guido van Rossuma110aa61994-08-29 12:50:44 +00002368#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002369#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002370#endif
2371
Collin Winter670e6922007-03-21 02:57:17 +00002372static void (*pyexitfunc)(void) = NULL;
2373/* For the atexit module. */
2374void _Py_PyAtExit(void (*func)(void))
2375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002377}
2378
2379static void
2380call_py_exitfuncs(void)
2381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 if (pyexitfunc == NULL)
2383 return;
Collin Winter670e6922007-03-21 02:57:17 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 (*pyexitfunc)();
2386 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002387}
2388
Antoine Pitrou011bd622009-10-20 21:52:47 +00002389/* Wait until threading._shutdown completes, provided
2390 the threading module was imported in the first place.
2391 The shutdown routine will wait until all non-daemon
2392 "threading" threads have completed. */
2393static void
2394wait_for_thread_shutdown(void)
2395{
2396#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 PyObject *result;
2398 PyThreadState *tstate = PyThreadState_GET();
2399 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2400 "threading");
2401 if (threading == NULL) {
2402 /* threading not imported */
2403 PyErr_Clear();
2404 return;
2405 }
2406 result = PyObject_CallMethod(threading, "_shutdown", "");
2407 if (result == NULL) {
2408 PyErr_WriteUnraisable(threading);
2409 }
2410 else {
2411 Py_DECREF(result);
2412 }
2413 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002414#endif
2415}
2416
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002417#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002418static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002419static int nexitfuncs = 0;
2420
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002421int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 if (nexitfuncs >= NEXITFUNCS)
2424 return -1;
2425 exitfuncs[nexitfuncs++] = func;
2426 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002427}
2428
Guido van Rossumcc283f51997-08-05 02:22:03 +00002429static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002430call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 while (nexitfuncs > 0)
2433 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 fflush(stdout);
2436 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002437}
2438
2439void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002440Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002445}
2446
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002447static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002448initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002449{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002450#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002452#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002453#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002455#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002456#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002458#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002460}
2461
Guido van Rossum7433b121997-02-14 19:45:36 +00002462
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002463/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2464 *
2465 * All of the code in this function must only use async-signal-safe functions,
2466 * listed at `man 7 signal` or
2467 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2468 */
2469void
2470_Py_RestoreSignals(void)
2471{
2472#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002474#endif
2475#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002477#endif
2478#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002480#endif
2481}
2482
2483
Guido van Rossum7433b121997-02-14 19:45:36 +00002484/*
2485 * The file descriptor fd is considered ``interactive'' if either
2486 * a) isatty(fd) is TRUE, or
2487 * b) the -i flag was given, and the filename associated with
2488 * the descriptor is NULL or "<stdin>" or "???".
2489 */
2490int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002491Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 if (isatty((int)fileno(fp)))
2494 return 1;
2495 if (!Py_InteractiveFlag)
2496 return 0;
2497 return (filename == NULL) ||
2498 (strcmp(filename, "<stdin>") == 0) ||
2499 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002500}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002501
2502
Tim Petersd08e3822003-04-17 15:24:21 +00002503#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002504#if defined(WIN32) && defined(_MSC_VER)
2505
2506/* Stack checking for Microsoft C */
2507
2508#include <malloc.h>
2509#include <excpt.h>
2510
Fred Drakee8de31c2000-08-31 05:38:39 +00002511/*
2512 * Return non-zero when we run out of memory on the stack; zero otherwise.
2513 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002514int
Fred Drake399739f2000-08-31 05:52:44 +00002515PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 __try {
2518 /* alloca throws a stack overflow exception if there's
2519 not enough space left on the stack */
2520 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2521 return 0;
2522 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2523 EXCEPTION_EXECUTE_HANDLER :
2524 EXCEPTION_CONTINUE_SEARCH) {
2525 int errcode = _resetstkoflw();
2526 if (errcode == 0)
2527 {
2528 Py_FatalError("Could not reset the stack!");
2529 }
2530 }
2531 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002532}
2533
2534#endif /* WIN32 && _MSC_VER */
2535
2536/* Alternate implementations can be added here... */
2537
2538#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002539
2540
2541/* Wrappers around sigaction() or signal(). */
2542
2543PyOS_sighandler_t
2544PyOS_getsig(int sig)
2545{
2546#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 struct sigaction context;
2548 if (sigaction(sig, NULL, &context) == -1)
2549 return SIG_ERR;
2550 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002551#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002553/* Special signal handling for the secure CRT in Visual Studio 2005 */
2554#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 switch (sig) {
2556 /* Only these signals are valid */
2557 case SIGINT:
2558 case SIGILL:
2559 case SIGFPE:
2560 case SIGSEGV:
2561 case SIGTERM:
2562 case SIGBREAK:
2563 case SIGABRT:
2564 break;
2565 /* Don't call signal() with other values or it will assert */
2566 default:
2567 return SIG_ERR;
2568 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002569#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 handler = signal(sig, SIG_IGN);
2571 if (handler != SIG_ERR)
2572 signal(sig, handler);
2573 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002574#endif
2575}
2576
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002577/*
2578 * All of the code in this function must only use async-signal-safe functions,
2579 * listed at `man 7 signal` or
2580 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2581 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002582PyOS_sighandler_t
2583PyOS_setsig(int sig, PyOS_sighandler_t handler)
2584{
2585#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 /* Some code in Modules/signalmodule.c depends on sigaction() being
2587 * used here if HAVE_SIGACTION is defined. Fix that if this code
2588 * changes to invalidate that assumption.
2589 */
2590 struct sigaction context, ocontext;
2591 context.sa_handler = handler;
2592 sigemptyset(&context.sa_mask);
2593 context.sa_flags = 0;
2594 if (sigaction(sig, &context, &ocontext) == -1)
2595 return SIG_ERR;
2596 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002597#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 PyOS_sighandler_t oldhandler;
2599 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002600#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002602#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002604#endif
2605}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002606
2607/* Deprecated C API functions still provided for binary compatiblity */
2608
2609#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002610PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002611PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614}
2615
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002616#undef PyParser_SimpleParseString
2617PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618PyParser_SimpleParseString(const char *str, int start)
2619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002622
2623#undef PyRun_AnyFile
2624PyAPI_FUNC(int)
2625PyRun_AnyFile(FILE *fp, const char *name)
2626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002628}
2629
2630#undef PyRun_AnyFileEx
2631PyAPI_FUNC(int)
2632PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002635}
2636
2637#undef PyRun_AnyFileFlags
2638PyAPI_FUNC(int)
2639PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002642}
2643
2644#undef PyRun_File
2645PyAPI_FUNC(PyObject *)
2646PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002649}
2650
2651#undef PyRun_FileEx
2652PyAPI_FUNC(PyObject *)
2653PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002656}
2657
2658#undef PyRun_FileFlags
2659PyAPI_FUNC(PyObject *)
2660PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002664}
2665
2666#undef PyRun_SimpleFile
2667PyAPI_FUNC(int)
2668PyRun_SimpleFile(FILE *f, const char *p)
2669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002671}
2672
2673#undef PyRun_SimpleFileEx
2674PyAPI_FUNC(int)
2675PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002678}
2679
2680
2681#undef PyRun_String
2682PyAPI_FUNC(PyObject *)
2683PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002686}
2687
2688#undef PyRun_SimpleString
2689PyAPI_FUNC(int)
2690PyRun_SimpleString(const char *s)
2691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002693}
2694
2695#undef Py_CompileString
2696PyAPI_FUNC(PyObject *)
2697Py_CompileString(const char *str, const char *p, int s)
2698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002700}
2701
2702#undef PyRun_InteractiveOne
2703PyAPI_FUNC(int)
2704PyRun_InteractiveOne(FILE *f, const char *p)
2705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002707}
2708
2709#undef PyRun_InteractiveLoop
2710PyAPI_FUNC(int)
2711PyRun_InteractiveLoop(FILE *f, const char *p)
2712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002714}
2715
2716#ifdef __cplusplus
2717}
2718#endif