blob: ad316136515b8faba2d297c429fd5b6c566c4af7 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
43 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#endif
45
46#ifdef __cplusplus
47extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000048#endif
49
Martin v. Löwis790465f2008-04-05 20:41:37 +000050extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000051
Guido van Rossum82598051997-03-05 00:20:32 +000052extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossumb73cc041993-11-01 16:28:59 +000054/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static void initmain(void);
Victor Stinner793b5312011-04-27 00:24:21 +020056static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020065static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000067static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000068static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000069static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000070extern void _PyUnicode_Init(void);
71extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020074extern int _PyFaulthandler_Init(void);
75extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000084int Py_QuietFlag; /* Needed by sysmodule.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 Stinner4ca28092011-03-20 23:09:03 +0100153 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000154 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000155 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000157 if (name_str == NULL) {
158 PyErr_NoMemory();
159 return NULL;
160 }
161 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000162
163error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000165 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000167}
Victor Stinner94908bb2010-08-18 21:23:25 +0000168
169#if defined(HAVE_LANGINFO_H) && defined(CODESET)
170static char*
171get_codeset(void)
172{
173 char* codeset = nl_langinfo(CODESET);
174 if (!codeset || codeset[0] == '\0') {
175 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
176 return NULL;
177 }
178 return get_codec_name(codeset);
179}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000180#endif
181
Guido van Rossuma027efa1997-05-05 20:56:21 +0000182void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000183Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyInterpreterState *interp;
186 PyThreadState *tstate;
187 PyObject *bimod, *sysmod, *pstderr;
188 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (initialized)
192 return;
193 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000194
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000195#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Set up the LC_CTYPE locale, so we can obtain
197 the locale's charset without having to switch
198 locales. */
199 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000200#endif
201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
203 Py_DebugFlag = add_flag(Py_DebugFlag, p);
204 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
205 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
206 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
207 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
208 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
209 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 interp = PyInterpreterState_New();
212 if (interp == NULL)
213 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 tstate = PyThreadState_New(interp);
216 if (tstate == NULL)
217 Py_FatalError("Py_Initialize: can't make first thread");
218 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000219
Victor Stinner6961bd62010-08-17 22:26:51 +0000220#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000221 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
222 destroying the GIL might fail when it is being referenced from
223 another running thread (see issue #9901).
224 Instead we destroy the previously created GIL here, which ensures
225 that we can call Py_Initialize / Py_Finalize multiple times. */
226 _PyEval_FiniThreads();
227
228 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000229 _PyGILState_Init(interp, tstate);
230#endif /* WITH_THREAD */
231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (!_PyFrame_Init())
235 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (!_PyLong_Init())
238 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (!PyByteArray_Init())
241 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 interp->modules = PyDict_New();
246 if (interp->modules == NULL)
247 Py_FatalError("Py_Initialize: can't make modules dictionary");
248 interp->modules_reloading = PyDict_New();
249 if (interp->modules_reloading == NULL)
250 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 /* Init Unicode implementation; relies on the codec registry */
253 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 bimod = _PyBuiltin_Init();
256 if (bimod == NULL)
257 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000258 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 interp->builtins = PyModule_GetDict(bimod);
260 if (interp->builtins == NULL)
261 Py_FatalError("Py_Initialize: can't initialize builtins dict");
262 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 /* initialize builtin exceptions */
265 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 sysmod = _PySys_Init();
268 if (sysmod == NULL)
269 Py_FatalError("Py_Initialize: can't initialize sys");
270 interp->sysdict = PyModule_GetDict(sysmod);
271 if (interp->sysdict == NULL)
272 Py_FatalError("Py_Initialize: can't initialize sys dict");
273 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000274 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 PySys_SetPath(Py_GetPath());
276 PyDict_SetItemString(interp->sysdict, "modules",
277 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 /* Set up a preliminary stderr printer until we have enough
280 infrastructure for the io module in place. */
281 pstderr = PyFile_NewStdPrinter(fileno(stderr));
282 if (pstderr == NULL)
283 Py_FatalError("Py_Initialize: can't set preliminary stderr");
284 PySys_SetObject("stderr", pstderr);
285 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000286 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000291
Victor Stinner024e37a2011-03-31 01:31:06 +0200292 /* initialize the faulthandler module */
293 if (_PyFaulthandler_Init())
294 Py_FatalError("Py_Initialize: can't initialize faulthandler");
295
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000296 /* Initialize _warnings. */
297 _PyWarnings_Init();
298
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000299 _PyTime_Init();
300
Victor Stinner793b5312011-04-27 00:24:21 +0200301 if (initfsencoding(interp) < 0)
302 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (install_sigs)
305 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 initmain(); /* Module __main__ */
308 if (initstdio() < 0)
309 Py_FatalError(
310 "Py_Initialize: can't initialize sys standard streams");
311
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000312 /* Initialize warnings. */
313 if (PySys_HasWarnOptions()) {
314 PyObject *warnings_module = PyImport_ImportModule("warnings");
315 if (warnings_module == NULL) {
316 fprintf(stderr, "'import warnings' failed; traceback:\n");
317 PyErr_Print();
318 }
319 Py_XDECREF(warnings_module);
320 }
321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 if (!Py_NoSiteFlag)
323 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000324}
325
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000326void
327Py_Initialize(void)
328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000330}
331
332
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000333#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000334extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000335#endif
336
Guido van Rossume8432ac2007-07-09 15:04:50 +0000337/* Flush stdout and stderr */
338
Neal Norwitz2bad9702007-08-27 06:19:22 +0000339static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000340flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 PyObject *fout = PySys_GetObject("stdout");
343 PyObject *ferr = PySys_GetObject("stderr");
344 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if (fout != NULL && fout != Py_None) {
347 tmp = PyObject_CallMethod(fout, "flush", "");
348 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000349 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 else
351 Py_DECREF(tmp);
352 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000353
Victor Stinner9467b212010-05-14 00:59:09 +0000354 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 tmp = PyObject_CallMethod(ferr, "flush", "");
356 if (tmp == NULL)
357 PyErr_Clear();
358 else
359 Py_DECREF(tmp);
360 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000361}
362
Guido van Rossum25ce5661997-08-02 03:10:38 +0000363/* Undo the effect of Py_Initialize().
364
365 Beware: if multiple interpreter and/or thread states exist, these
366 are not wiped out; only the current thread and interpreter state
367 are deleted. But since everything else is deleted, those other
368 interpreter and thread states should no longer be used.
369
370 (XXX We should do better, e.g. wipe out all interpreters and
371 threads.)
372
373 Locking: as above.
374
375*/
376
377void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000378Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyInterpreterState *interp;
381 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 if (!initialized)
384 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 /* The interpreter is still entirely intact at this point, and the
389 * exit funcs may be relying on that. In particular, if some thread
390 * or exit func is still waiting to do an import, the import machinery
391 * expects Py_IsInitialized() to return true. So don't say the
392 * interpreter is uninitialized until after the exit funcs have run.
393 * Note that Threading.py uses an exit func to do a join on all the
394 * threads created thru it, so this also protects pending imports in
395 * the threads created via Threading.
396 */
397 call_py_exitfuncs();
398 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 /* Flush stdout+stderr */
401 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 /* Get current thread state and interpreter pointer */
404 tstate = PyThreadState_GET();
405 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 /* Disable signal handling */
408 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 /* Clear type lookup cache */
411 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 /* Collect garbage. This may call finalizers; it's nice to call these
414 * before all modules are destroyed.
415 * XXX If a __del__ or weakref callback is triggered here, and tries to
416 * XXX import a module, bad things can happen, because Python no
417 * XXX longer believes it's initialized.
418 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
419 * XXX is easy to provoke that way. I've also seen, e.g.,
420 * XXX Exception exceptions.ImportError: 'No module named sha'
421 * XXX in <function callback at 0x008F5718> ignored
422 * XXX but I'm unclear on exactly how that one happens. In any case,
423 * XXX I haven't seen a real-life report of either of these.
424 */
425 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000426#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 /* With COUNT_ALLOCS, it helps to run GC multiple times:
428 each collection might release some types from the type
429 list, so they become garbage. */
430 while (PyGC_Collect() > 0)
431 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000432#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000433 /* We run this while most interpreter state is still alive, so that
434 debug information can be printed out */
435 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 /* Destroy all modules */
438 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 /* Flush stdout+stderr (again, in case more was printed) */
441 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* Collect final garbage. This disposes of cycles created by
444 * new-style class definitions, for example.
445 * XXX This is disabled because it caused too many problems. If
446 * XXX a __del__ or weakref callback triggers here, Python code has
447 * XXX a hard time running, because even the sys module has been
448 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
449 * XXX One symptom is a sequence of information-free messages
450 * XXX coming from threads (if a __del__ or callback is invoked,
451 * XXX other threads can execute too, and any exception they encounter
452 * XXX triggers a comedy of errors as subsystem after subsystem
453 * XXX fails to find what it *expects* to find in sys to help report
454 * XXX the exception and consequent unexpected failures). I've also
455 * XXX seen segfaults then, after adding print statements to the
456 * XXX Python code getting called.
457 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000458#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000460#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
463 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000464
Victor Stinner024e37a2011-03-31 01:31:06 +0200465 /* unload faulthandler module */
466 _PyFaulthandler_Fini();
467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000469#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000471#endif
472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000474
Tim Peters9cf25ce2003-04-17 15:21:01 +0000475#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* Display all objects still alive -- this can invoke arbitrary
477 * __repr__ overrides, so requires a mostly-intact interpreter.
478 * Alas, a lot of stuff may still be alive now that will be cleaned
479 * up later.
480 */
481 if (Py_GETENV("PYTHONDUMPREFS"))
482 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000483#endif /* Py_TRACE_REFS */
484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* Clear interpreter state */
486 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 /* Now we decref the exception classes. After this point nothing
489 can raise an exception. That's okay, because each Fini() method
490 below has been checked to make sure no exceptions are ever
491 raised.
492 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000497#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000499#endif /* WITH_THREAD */
500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* Delete current thread */
502 PyThreadState_Swap(NULL);
503 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 /* Sundry finalizers */
506 PyMethod_Fini();
507 PyFrame_Fini();
508 PyCFunction_Fini();
509 PyTuple_Fini();
510 PyList_Fini();
511 PySet_Fini();
512 PyBytes_Fini();
513 PyByteArray_Fini();
514 PyLong_Fini();
515 PyFloat_Fini();
516 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* Cleanup Unicode implementation */
519 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000522 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 free((char*)Py_FileSystemDefaultEncoding);
524 Py_FileSystemDefaultEncoding = NULL;
525 }
Christian Heimesc8967002007-11-30 10:18:26 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 /* XXX Still allocated:
528 - various static ad-hoc pointers to interned strings
529 - int and float free list blocks
530 - whatever various modules and libraries allocate
531 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000532
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000534
Tim Peters269b2a62003-04-17 19:52:29 +0000535#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* Display addresses (& refcnts) of all objects still alive.
537 * An address can be used to find the repr of the object, printed
538 * above by _Py_PrintReferences.
539 */
540 if (Py_GETENV("PYTHONDUMPREFS"))
541 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000542#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000543#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (Py_GETENV("PYTHONMALLOCSTATS"))
545 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000546#endif
547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000549}
550
551/* Create and initialize a new interpreter and thread, and return the
552 new thread. This requires that Py_Initialize() has been called
553 first.
554
555 Unsuccessful initialization yields a NULL pointer. Note that *no*
556 exception information is available even in this case -- the
557 exception information is held in the thread, and there is no
558 thread.
559
560 Locking: as above.
561
562*/
563
564PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000565Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 PyInterpreterState *interp;
568 PyThreadState *tstate, *save_tstate;
569 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (!initialized)
572 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 interp = PyInterpreterState_New();
575 if (interp == NULL)
576 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 tstate = PyThreadState_New(interp);
579 if (tstate == NULL) {
580 PyInterpreterState_Delete(interp);
581 return NULL;
582 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 interp->modules = PyDict_New();
589 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590
Victor Stinner49d3f252010-10-17 01:24:53 +0000591 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (bimod != NULL) {
593 interp->builtins = PyModule_GetDict(bimod);
594 if (interp->builtins == NULL)
595 goto handle_error;
596 Py_INCREF(interp->builtins);
597 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* initialize builtin exceptions */
600 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000601
Victor Stinner49d3f252010-10-17 01:24:53 +0000602 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (bimod != NULL && sysmod != NULL) {
604 PyObject *pstderr;
605 interp->sysdict = PyModule_GetDict(sysmod);
606 if (interp->sysdict == NULL)
607 goto handle_error;
608 Py_INCREF(interp->sysdict);
609 PySys_SetPath(Py_GetPath());
610 PyDict_SetItemString(interp->sysdict, "modules",
611 interp->modules);
612 /* Set up a preliminary stderr printer until we have enough
613 infrastructure for the io module in place. */
614 pstderr = PyFile_NewStdPrinter(fileno(stderr));
615 if (pstderr == NULL)
616 Py_FatalError("Py_Initialize: can't set preliminary stderr");
617 PySys_SetObject("stderr", pstderr);
618 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000619 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200622
623 if (initfsencoding(interp) < 0)
624 goto handle_error;
625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (initstdio() < 0)
627 Py_FatalError(
628 "Py_Initialize: can't initialize sys standard streams");
629 initmain();
630 if (!Py_NoSiteFlag)
631 initsite();
632 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (!PyErr_Occurred())
635 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000636
Thomas Wouters89f507f2006-12-13 04:49:30 +0000637handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000639
Victor Stinnerc40a3502011-04-27 00:20:27 +0200640 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyThreadState_Clear(tstate);
642 PyThreadState_Swap(save_tstate);
643 PyThreadState_Delete(tstate);
644 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000647}
648
649/* Delete an interpreter and its last thread. This requires that the
650 given thread state is current, that the thread has no remaining
651 frames, and that it is its interpreter's only remaining thread.
652 It is a fatal error to violate these constraints.
653
654 (Py_Finalize() doesn't have these constraints -- it zaps
655 everything, regardless.)
656
657 Locking: as above.
658
659*/
660
661void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000662Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 if (tstate != PyThreadState_GET())
667 Py_FatalError("Py_EndInterpreter: thread is not current");
668 if (tstate->frame != NULL)
669 Py_FatalError("Py_EndInterpreter: thread still has a frame");
670 if (tstate != interp->tstate_head || tstate->next != NULL)
671 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyImport_Cleanup();
674 PyInterpreterState_Clear(interp);
675 PyThreadState_Swap(NULL);
676 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000677}
678
Martin v. Löwis790465f2008-04-05 20:41:37 +0000679static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000680
681void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000682Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if (pn && *pn)
685 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000686}
687
Martin v. Löwis790465f2008-04-05 20:41:37 +0000688wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000689Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000692}
693
Martin v. Löwis790465f2008-04-05 20:41:37 +0000694static wchar_t *default_home = NULL;
695static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000696
697void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000698Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000701}
702
Martin v. Löwis790465f2008-04-05 20:41:37 +0000703wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000704Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 wchar_t *home = default_home;
707 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
708 char* chome = Py_GETENV("PYTHONHOME");
709 if (chome) {
710 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
711 if (r != (size_t)-1 && r <= PATH_MAX)
712 home = env_home;
713 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 }
716 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000717}
718
Guido van Rossum6135a871995-01-09 17:53:26 +0000719/* Create __main__ module */
720
721static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000722initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 PyObject *m, *d;
725 m = PyImport_AddModule("__main__");
726 if (m == NULL)
727 Py_FatalError("can't create __main__ module");
728 d = PyModule_GetDict(m);
729 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
730 PyObject *bimod = PyImport_ImportModule("builtins");
731 if (bimod == NULL ||
732 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
733 Py_FatalError("can't add __builtins__ to __main__");
734 Py_DECREF(bimod);
735 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000736}
737
Victor Stinner793b5312011-04-27 00:24:21 +0200738static int
739initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000740{
741 PyObject *codec;
742#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000743 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000744
Victor Stinner7f84ab52010-06-11 00:36:33 +0000745 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000746 /* On Unix, set the file system encoding according to the
747 user's preference, if the CODESET names a well-known
748 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000749 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000750 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000751 if (codeset == NULL)
752 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000753
Victor Stinnere4743092010-10-19 00:05:51 +0000754 Py_FileSystemDefaultEncoding = codeset;
755 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200756 interp->fscodec_initialized = 1;
757 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000758 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000759#endif
760
761 /* the encoding is mbcs, utf-8 or ascii */
762 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
763 if (!codec) {
764 /* Such error can only occurs in critical situations: no more
765 * memory, import a module of the standard library failed,
766 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200767 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000768 }
Victor Stinner793b5312011-04-27 00:24:21 +0200769 Py_DECREF(codec);
770 interp->fscodec_initialized = 1;
771 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000772}
773
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000774/* Import the site module (not into __main__ though) */
775
776static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000777initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyObject *m;
780 m = PyImport_ImportModule("site");
781 if (m == NULL) {
782 PyErr_Print();
783 Py_Finalize();
784 exit(1);
785 }
786 else {
787 Py_DECREF(m);
788 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000789}
790
Antoine Pitrou05608432009-01-09 18:53:14 +0000791static PyObject*
792create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 int fd, int write_mode, char* name,
794 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
797 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000798 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 PyObject *line_buffering;
800 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 /* stdin is always opened in buffered mode, first because it shouldn't
803 make a difference in common use cases, second because TextIOWrapper
804 depends on the presence of a read1() method which only exists on
805 buffered streams.
806 */
807 if (Py_UnbufferedStdioFlag && write_mode)
808 buffering = 0;
809 else
810 buffering = -1;
811 if (write_mode)
812 mode = "wb";
813 else
814 mode = "rb";
815 buf = PyObject_CallMethod(io, "open", "isiOOOi",
816 fd, mode, buffering,
817 Py_None, Py_None, Py_None, 0);
818 if (buf == NULL)
819 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (buffering) {
822 raw = PyObject_GetAttrString(buf, "raw");
823 if (raw == NULL)
824 goto error;
825 }
826 else {
827 raw = buf;
828 Py_INCREF(raw);
829 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 text = PyUnicode_FromString(name);
832 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
833 goto error;
834 res = PyObject_CallMethod(raw, "isatty", "");
835 if (res == NULL)
836 goto error;
837 isatty = PyObject_IsTrue(res);
838 Py_DECREF(res);
839 if (isatty == -1)
840 goto error;
841 if (isatty || Py_UnbufferedStdioFlag)
842 line_buffering = Py_True;
843 else
844 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 Py_CLEAR(raw);
847 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000848
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000849 newline = "\n";
850#ifdef MS_WINDOWS
851 if (!write_mode) {
852 /* translate \r\n to \n for sys.stdin on Windows */
853 newline = NULL;
854 }
855#endif
856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
858 buf, encoding, errors,
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000859 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 Py_CLEAR(buf);
861 if (stream == NULL)
862 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (write_mode)
865 mode = "w";
866 else
867 mode = "r";
868 text = PyUnicode_FromString(mode);
869 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
870 goto error;
871 Py_CLEAR(text);
872 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000873
874error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 Py_XDECREF(buf);
876 Py_XDECREF(stream);
877 Py_XDECREF(text);
878 Py_XDECREF(raw);
879 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000880}
881
Georg Brandl1a3284e2007-12-02 09:40:06 +0000882/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000883static int
884initstdio(void)
885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 PyObject *iomod = NULL, *wrapper;
887 PyObject *bimod = NULL;
888 PyObject *m;
889 PyObject *std = NULL;
890 int status = 0, fd;
891 PyObject * encoding_attr;
892 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Hack to avoid a nasty recursion issue when Python is invoked
895 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
896 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
897 goto error;
898 }
899 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
902 goto error;
903 }
904 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000905
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (!(bimod = PyImport_ImportModule("builtins"))) {
907 goto error;
908 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 if (!(iomod = PyImport_ImportModule("io"))) {
911 goto error;
912 }
913 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
914 goto error;
915 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* Set builtins.open */
918 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000919 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 goto error;
921 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000922 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 encoding = Py_GETENV("PYTHONIOENCODING");
925 errors = NULL;
926 if (encoding) {
927 encoding = strdup(encoding);
928 errors = strchr(encoding, ':');
929 if (errors) {
930 *errors = '\0';
931 errors++;
932 }
933 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* Set sys.stdin */
936 fd = fileno(stdin);
937 /* Under some conditions stdin, stdout and stderr may not be connected
938 * and fileno() may point to an invalid file descriptor. For example
939 * GUI apps don't have valid standard streams by default.
940 */
941 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000942#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 std = Py_None;
944 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000945#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000947#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 }
949 else {
950 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
951 if (std == NULL)
952 goto error;
953 } /* if (fd < 0) */
954 PySys_SetObject("__stdin__", std);
955 PySys_SetObject("stdin", std);
956 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 /* Set sys.stdout */
959 fd = fileno(stdout);
960 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000961#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 std = Py_None;
963 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000964#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000966#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 }
968 else {
969 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
970 if (std == NULL)
971 goto error;
972 } /* if (fd < 0) */
973 PySys_SetObject("__stdout__", std);
974 PySys_SetObject("stdout", std);
975 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000976
Guido van Rossum98297ee2007-11-06 21:34:58 +0000977#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 /* Set sys.stderr, replaces the preliminary stderr */
979 fd = fileno(stderr);
980 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000981#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 std = Py_None;
983 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000984#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000986#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 }
988 else {
989 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
990 if (std == NULL)
991 goto error;
992 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 /* Same as hack above, pre-import stderr's codec to avoid recursion
995 when import.c tries to write to stderr in verbose mode. */
996 encoding_attr = PyObject_GetAttrString(std, "encoding");
997 if (encoding_attr != NULL) {
998 const char * encoding;
999 encoding = _PyUnicode_AsString(encoding_attr);
1000 if (encoding != NULL) {
1001 _PyCodec_Lookup(encoding);
1002 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001003 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 }
1005 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 PySys_SetObject("__stderr__", std);
1008 PySys_SetObject("stderr", std);
1009 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001010#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001013 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 status = -1;
1015 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (encoding)
1018 free(encoding);
1019 Py_XDECREF(bimod);
1020 Py_XDECREF(iomod);
1021 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001022}
1023
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001024/* Parse input from a file and execute it */
1025
1026int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001027PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (filename == NULL)
1031 filename = "???";
1032 if (Py_FdIsInteractive(fp, filename)) {
1033 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1034 if (closeit)
1035 fclose(fp);
1036 return err;
1037 }
1038 else
1039 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001040}
1041
1042int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001043PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 PyObject *v;
1046 int ret;
1047 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 if (flags == NULL) {
1050 flags = &local_flags;
1051 local_flags.cf_flags = 0;
1052 }
1053 v = PySys_GetObject("ps1");
1054 if (v == NULL) {
1055 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1056 Py_XDECREF(v);
1057 }
1058 v = PySys_GetObject("ps2");
1059 if (v == NULL) {
1060 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1061 Py_XDECREF(v);
1062 }
1063 for (;;) {
1064 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1065 PRINT_TOTAL_REFS();
1066 if (ret == E_EOF)
1067 return 0;
1068 /*
1069 if (ret == E_NOMEM)
1070 return -1;
1071 */
1072 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001073}
1074
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001075/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001076static int PARSER_FLAGS(PyCompilerFlags *flags)
1077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 int parser_flags = 0;
1079 if (!flags)
1080 return 0;
1081 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1082 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1083 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1084 parser_flags |= PyPARSE_IGNORE_COOKIE;
1085 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1086 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1087 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001088}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001089
Thomas Wouters89f507f2006-12-13 04:49:30 +00001090#if 0
1091/* Keep an example of flags with future keyword support. */
1092#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1094 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1095 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1096 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001097#endif
1098
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001099int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001100PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 PyObject *m, *d, *v, *w, *oenc = NULL;
1103 mod_ty mod;
1104 PyArena *arena;
1105 char *ps1 = "", *ps2 = "", *enc = NULL;
1106 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 if (fp == stdin) {
1109 /* Fetch encoding from sys.stdin */
1110 v = PySys_GetObject("stdin");
1111 if (v == NULL || v == Py_None)
1112 return -1;
1113 oenc = PyObject_GetAttrString(v, "encoding");
1114 if (!oenc)
1115 return -1;
1116 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001117 if (enc == NULL)
1118 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 }
1120 v = PySys_GetObject("ps1");
1121 if (v != NULL) {
1122 v = PyObject_Str(v);
1123 if (v == NULL)
1124 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001125 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001127 if (ps1 == NULL) {
1128 PyErr_Clear();
1129 ps1 = "";
1130 }
1131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 }
1133 w = PySys_GetObject("ps2");
1134 if (w != NULL) {
1135 w = PyObject_Str(w);
1136 if (w == NULL)
1137 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001138 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001140 if (ps2 == NULL) {
1141 PyErr_Clear();
1142 ps2 = "";
1143 }
1144 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 }
1146 arena = PyArena_New();
1147 if (arena == NULL) {
1148 Py_XDECREF(v);
1149 Py_XDECREF(w);
1150 Py_XDECREF(oenc);
1151 return -1;
1152 }
1153 mod = PyParser_ASTFromFile(fp, filename, enc,
1154 Py_single_input, ps1, ps2,
1155 flags, &errcode, arena);
1156 Py_XDECREF(v);
1157 Py_XDECREF(w);
1158 Py_XDECREF(oenc);
1159 if (mod == NULL) {
1160 PyArena_Free(arena);
1161 if (errcode == E_EOF) {
1162 PyErr_Clear();
1163 return E_EOF;
1164 }
1165 PyErr_Print();
1166 return -1;
1167 }
1168 m = PyImport_AddModule("__main__");
1169 if (m == NULL) {
1170 PyArena_Free(arena);
1171 return -1;
1172 }
1173 d = PyModule_GetDict(m);
1174 v = run_mod(mod, filename, d, d, flags, arena);
1175 PyArena_Free(arena);
1176 flush_io();
1177 if (v == NULL) {
1178 PyErr_Print();
1179 return -1;
1180 }
1181 Py_DECREF(v);
1182 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001183}
1184
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001185/* Check whether a file maybe a pyc file: Look at the extension,
1186 the file type, and, if we may close it, at the first few bytes. */
1187
1188static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001189maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1192 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 /* Only look into the file if we are allowed to close it, since
1195 it then should also be seekable. */
1196 if (closeit) {
1197 /* Read only two bytes of the magic. If the file was opened in
1198 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1199 be read as they are on disk. */
1200 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1201 unsigned char buf[2];
1202 /* Mess: In case of -x, the stream is NOT at its start now,
1203 and ungetc() was used to push back the first newline,
1204 which makes the current stream position formally undefined,
1205 and a x-platform nightmare.
1206 Unfortunately, we have no direct way to know whether -x
1207 was specified. So we use a terrible hack: if the current
1208 stream position is not 0, we assume -x was specified, and
1209 give up. Bug 132850 on SourceForge spells out the
1210 hopelessness of trying anything else (fseek and ftell
1211 don't work predictably x-platform for text-mode files).
1212 */
1213 int ispyc = 0;
1214 if (ftell(fp) == 0) {
1215 if (fread(buf, 1, 2, fp) == 2 &&
1216 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1217 ispyc = 1;
1218 rewind(fp);
1219 }
1220 return ispyc;
1221 }
1222 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001223}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001224
Guido van Rossum0df002c2000-08-27 19:21:52 +00001225int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001226PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 PyObject *m, *d, *v;
1230 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001231 int set_file_name = 0, ret;
1232 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 m = PyImport_AddModule("__main__");
1235 if (m == NULL)
1236 return -1;
1237 d = PyModule_GetDict(m);
1238 if (PyDict_GetItemString(d, "__file__") == NULL) {
1239 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001240 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (f == NULL)
1242 return -1;
1243 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1244 Py_DECREF(f);
1245 return -1;
1246 }
1247 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1248 return -1;
1249 set_file_name = 1;
1250 Py_DECREF(f);
1251 }
1252 len = strlen(filename);
1253 ext = filename + len - (len > 4 ? 4 : 0);
1254 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1255 /* Try to run a pyc file. First, re-open in binary */
1256 if (closeit)
1257 fclose(fp);
1258 if ((fp = fopen(filename, "rb")) == NULL) {
1259 fprintf(stderr, "python: Can't reopen .pyc file\n");
1260 ret = -1;
1261 goto done;
1262 }
1263 /* Turn on optimization if a .pyo file is given */
1264 if (strcmp(ext, ".pyo") == 0)
1265 Py_OptimizeFlag = 1;
1266 v = run_pyc_file(fp, filename, d, d, flags);
1267 } else {
1268 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1269 closeit, flags);
1270 }
1271 flush_io();
1272 if (v == NULL) {
1273 PyErr_Print();
1274 ret = -1;
1275 goto done;
1276 }
1277 Py_DECREF(v);
1278 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001279 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1281 PyErr_Clear();
1282 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001283}
1284
1285int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001286PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 PyObject *m, *d, *v;
1289 m = PyImport_AddModule("__main__");
1290 if (m == NULL)
1291 return -1;
1292 d = PyModule_GetDict(m);
1293 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1294 if (v == NULL) {
1295 PyErr_Print();
1296 return -1;
1297 }
1298 Py_DECREF(v);
1299 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001300}
1301
Barry Warsaw035574d1997-08-29 22:07:17 +00001302static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001303parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 long hold;
1307 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 /* old style errors */
1310 if (PyTuple_Check(err))
1311 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1312 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (! (v = PyObject_GetAttrString(err, "msg")))
1317 goto finally;
1318 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (!(v = PyObject_GetAttrString(err, "filename")))
1321 goto finally;
1322 if (v == Py_None)
1323 *filename = NULL;
1324 else if (! (*filename = _PyUnicode_AsString(v)))
1325 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 Py_DECREF(v);
1328 if (!(v = PyObject_GetAttrString(err, "lineno")))
1329 goto finally;
1330 hold = PyLong_AsLong(v);
1331 Py_DECREF(v);
1332 v = NULL;
1333 if (hold < 0 && PyErr_Occurred())
1334 goto finally;
1335 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 if (!(v = PyObject_GetAttrString(err, "offset")))
1338 goto finally;
1339 if (v == Py_None) {
1340 *offset = -1;
1341 Py_DECREF(v);
1342 v = NULL;
1343 } else {
1344 hold = PyLong_AsLong(v);
1345 Py_DECREF(v);
1346 v = NULL;
1347 if (hold < 0 && PyErr_Occurred())
1348 goto finally;
1349 *offset = (int)hold;
1350 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 if (!(v = PyObject_GetAttrString(err, "text")))
1353 goto finally;
1354 if (v == Py_None)
1355 *text = NULL;
1356 else if (!PyUnicode_Check(v) ||
1357 !(*text = _PyUnicode_AsString(v)))
1358 goto finally;
1359 Py_DECREF(v);
1360 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001361
1362finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 Py_XDECREF(v);
1364 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001365}
1366
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001367void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001368PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001371}
1372
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001373static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001374print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 char *nl;
1377 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001378 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1379 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 for (;;) {
1381 nl = strchr(text, '\n');
1382 if (nl == NULL || nl-text >= offset)
1383 break;
1384 offset -= (int)(nl+1-text);
1385 text = nl+1;
1386 }
1387 while (*text == ' ' || *text == '\t') {
1388 text++;
1389 offset--;
1390 }
1391 }
1392 PyFile_WriteString(" ", f);
1393 PyFile_WriteString(text, f);
1394 if (*text == '\0' || text[strlen(text)-1] != '\n')
1395 PyFile_WriteString("\n", f);
1396 if (offset == -1)
1397 return;
1398 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001399 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001402}
1403
Guido van Rossum66e8e862001-03-23 17:54:43 +00001404static void
1405handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 PyObject *exception, *value, *tb;
1408 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (Py_InspectFlag)
1411 /* Don't exit if -i flag was given. This flag is set to 0
1412 * when entering interactive mode for inspecting. */
1413 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 PyErr_Fetch(&exception, &value, &tb);
1416 fflush(stdout);
1417 if (value == NULL || value == Py_None)
1418 goto done;
1419 if (PyExceptionInstance_Check(value)) {
1420 /* The error code should be in the `code' attribute. */
1421 PyObject *code = PyObject_GetAttrString(value, "code");
1422 if (code) {
1423 Py_DECREF(value);
1424 value = code;
1425 if (value == Py_None)
1426 goto done;
1427 }
1428 /* If we failed to dig out the 'code' attribute,
1429 just let the else clause below print the error. */
1430 }
1431 if (PyLong_Check(value))
1432 exitcode = (int)PyLong_AsLong(value);
1433 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001434 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001435 if (sys_stderr != NULL && sys_stderr != Py_None) {
1436 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1437 } else {
1438 PyObject_Print(value, stderr, Py_PRINT_RAW);
1439 fflush(stderr);
1440 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PySys_WriteStderr("\n");
1442 exitcode = 1;
1443 }
Tim Peterscf615b52003-04-19 18:47:02 +00001444 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 /* Restore and clear the exception info, in order to properly decref
1446 * the exception, value, and traceback. If we just exit instead,
1447 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1448 * some finalizers from running.
1449 */
1450 PyErr_Restore(exception, value, tb);
1451 PyErr_Clear();
1452 Py_Exit(exitcode);
1453 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001454}
1455
1456void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001457PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1462 handle_system_exit();
1463 }
1464 PyErr_Fetch(&exception, &v, &tb);
1465 if (exception == NULL)
1466 return;
1467 PyErr_NormalizeException(&exception, &v, &tb);
1468 if (tb == NULL) {
1469 tb = Py_None;
1470 Py_INCREF(tb);
1471 }
1472 PyException_SetTraceback(v, tb);
1473 if (exception == NULL)
1474 return;
1475 /* Now we know v != NULL too */
1476 if (set_sys_last_vars) {
1477 PySys_SetObject("last_type", exception);
1478 PySys_SetObject("last_value", v);
1479 PySys_SetObject("last_traceback", tb);
1480 }
1481 hook = PySys_GetObject("excepthook");
1482 if (hook) {
1483 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1484 PyObject *result = PyEval_CallObject(hook, args);
1485 if (result == NULL) {
1486 PyObject *exception2, *v2, *tb2;
1487 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1488 handle_system_exit();
1489 }
1490 PyErr_Fetch(&exception2, &v2, &tb2);
1491 PyErr_NormalizeException(&exception2, &v2, &tb2);
1492 /* It should not be possible for exception2 or v2
1493 to be NULL. However PyErr_Display() can't
1494 tolerate NULLs, so just be safe. */
1495 if (exception2 == NULL) {
1496 exception2 = Py_None;
1497 Py_INCREF(exception2);
1498 }
1499 if (v2 == NULL) {
1500 v2 = Py_None;
1501 Py_INCREF(v2);
1502 }
1503 fflush(stdout);
1504 PySys_WriteStderr("Error in sys.excepthook:\n");
1505 PyErr_Display(exception2, v2, tb2);
1506 PySys_WriteStderr("\nOriginal exception was:\n");
1507 PyErr_Display(exception, v, tb);
1508 Py_DECREF(exception2);
1509 Py_DECREF(v2);
1510 Py_XDECREF(tb2);
1511 }
1512 Py_XDECREF(result);
1513 Py_XDECREF(args);
1514 } else {
1515 PySys_WriteStderr("sys.excepthook is missing\n");
1516 PyErr_Display(exception, v, tb);
1517 }
1518 Py_XDECREF(exception);
1519 Py_XDECREF(v);
1520 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001521}
1522
Benjamin Petersone6528212008-07-15 15:32:09 +00001523static void
1524print_exception(PyObject *f, PyObject *value)
1525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 int err = 0;
1527 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 if (!PyExceptionInstance_Check(value)) {
1530 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1531 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1532 PyFile_WriteString(" found\n", f);
1533 return;
1534 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 Py_INCREF(value);
1537 fflush(stdout);
1538 type = (PyObject *) Py_TYPE(value);
1539 tb = PyException_GetTraceback(value);
1540 if (tb && tb != Py_None)
1541 err = PyTraceBack_Print(tb, f);
1542 if (err == 0 &&
1543 PyObject_HasAttrString(value, "print_file_and_line"))
1544 {
1545 PyObject *message;
1546 const char *filename, *text;
1547 int lineno, offset;
1548 if (!parse_syntax_error(value, &message, &filename,
1549 &lineno, &offset, &text))
1550 PyErr_Clear();
1551 else {
1552 char buf[10];
1553 PyFile_WriteString(" File \"", f);
1554 if (filename == NULL)
1555 PyFile_WriteString("<string>", f);
1556 else
1557 PyFile_WriteString(filename, f);
1558 PyFile_WriteString("\", line ", f);
1559 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1560 PyFile_WriteString(buf, f);
1561 PyFile_WriteString("\n", f);
1562 if (text != NULL)
1563 print_error_text(f, offset, text);
1564 Py_DECREF(value);
1565 value = message;
1566 /* Can't be bothered to check all those
1567 PyFile_WriteString() calls */
1568 if (PyErr_Occurred())
1569 err = -1;
1570 }
1571 }
1572 if (err) {
1573 /* Don't do anything else */
1574 }
1575 else {
1576 PyObject* moduleName;
1577 char* className;
1578 assert(PyExceptionClass_Check(type));
1579 className = PyExceptionClass_Name(type);
1580 if (className != NULL) {
1581 char *dot = strrchr(className, '.');
1582 if (dot != NULL)
1583 className = dot+1;
1584 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 moduleName = PyObject_GetAttrString(type, "__module__");
1587 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1588 {
1589 Py_DECREF(moduleName);
1590 err = PyFile_WriteString("<unknown>", f);
1591 }
1592 else {
1593 char* modstr = _PyUnicode_AsString(moduleName);
1594 if (modstr && strcmp(modstr, "builtins"))
1595 {
1596 err = PyFile_WriteString(modstr, f);
1597 err += PyFile_WriteString(".", f);
1598 }
1599 Py_DECREF(moduleName);
1600 }
1601 if (err == 0) {
1602 if (className == NULL)
1603 err = PyFile_WriteString("<unknown>", f);
1604 else
1605 err = PyFile_WriteString(className, f);
1606 }
1607 }
1608 if (err == 0 && (value != Py_None)) {
1609 PyObject *s = PyObject_Str(value);
1610 /* only print colon if the str() of the
1611 object is not the empty string
1612 */
1613 if (s == NULL)
1614 err = -1;
1615 else if (!PyUnicode_Check(s) ||
1616 PyUnicode_GetSize(s) != 0)
1617 err = PyFile_WriteString(": ", f);
1618 if (err == 0)
1619 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1620 Py_XDECREF(s);
1621 }
1622 /* try to write a newline in any case */
1623 err += PyFile_WriteString("\n", f);
1624 Py_XDECREF(tb);
1625 Py_DECREF(value);
1626 /* If an error happened here, don't show it.
1627 XXX This is wrong, but too many callers rely on this behavior. */
1628 if (err != 0)
1629 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001630}
1631
1632static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 "\nThe above exception was the direct cause "
1634 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001635
1636static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 "\nDuring handling of the above exception, "
1638 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001639
1640static void
1641print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 int err = 0, res;
1644 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 if (seen != NULL) {
1647 /* Exception chaining */
1648 if (PySet_Add(seen, value) == -1)
1649 PyErr_Clear();
1650 else if (PyExceptionInstance_Check(value)) {
1651 cause = PyException_GetCause(value);
1652 context = PyException_GetContext(value);
1653 if (cause) {
1654 res = PySet_Contains(seen, cause);
1655 if (res == -1)
1656 PyErr_Clear();
1657 if (res == 0) {
1658 print_exception_recursive(
1659 f, cause, seen);
1660 err |= PyFile_WriteString(
1661 cause_message, f);
1662 }
1663 }
1664 else if (context) {
1665 res = PySet_Contains(seen, context);
1666 if (res == -1)
1667 PyErr_Clear();
1668 if (res == 0) {
1669 print_exception_recursive(
1670 f, context, seen);
1671 err |= PyFile_WriteString(
1672 context_message, f);
1673 }
1674 }
1675 Py_XDECREF(context);
1676 Py_XDECREF(cause);
1677 }
1678 }
1679 print_exception(f, value);
1680 if (err != 0)
1681 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001682}
1683
Thomas Wouters477c8d52006-05-27 19:21:47 +00001684void
1685PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyObject *seen;
1688 PyObject *f = PySys_GetObject("stderr");
1689 if (f == Py_None) {
1690 /* pass */
1691 }
1692 else if (f == NULL) {
1693 _PyObject_Dump(value);
1694 fprintf(stderr, "lost sys.stderr\n");
1695 }
1696 else {
1697 /* We choose to ignore seen being possibly NULL, and report
1698 at least the main exception (it could be a MemoryError).
1699 */
1700 seen = PySet_New(NULL);
1701 if (seen == NULL)
1702 PyErr_Clear();
1703 print_exception_recursive(f, value, seen);
1704 Py_XDECREF(seen);
1705 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001706}
1707
Guido van Rossum82598051997-03-05 00:20:32 +00001708PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001709PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyObject *ret = NULL;
1713 mod_ty mod;
1714 PyArena *arena = PyArena_New();
1715 if (arena == NULL)
1716 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1719 if (mod != NULL)
1720 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1721 PyArena_Free(arena);
1722 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001723}
1724
1725PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001726PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 PyObject *ret;
1730 mod_ty mod;
1731 PyArena *arena = PyArena_New();
1732 if (arena == NULL)
1733 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1736 flags, NULL, arena);
1737 if (closeit)
1738 fclose(fp);
1739 if (mod == NULL) {
1740 PyArena_Free(arena);
1741 return NULL;
1742 }
1743 ret = run_mod(mod, filename, globals, locals, flags, arena);
1744 PyArena_Free(arena);
1745 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001746}
1747
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001748static void
1749flush_io(void)
1750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 PyObject *f, *r;
1752 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 /* Save the current exception */
1755 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 f = PySys_GetObject("stderr");
1758 if (f != NULL) {
1759 r = PyObject_CallMethod(f, "flush", "");
1760 if (r)
1761 Py_DECREF(r);
1762 else
1763 PyErr_Clear();
1764 }
1765 f = PySys_GetObject("stdout");
1766 if (f != NULL) {
1767 r = PyObject_CallMethod(f, "flush", "");
1768 if (r)
1769 Py_DECREF(r);
1770 else
1771 PyErr_Clear();
1772 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001775}
1776
Guido van Rossum82598051997-03-05 00:20:32 +00001777static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001778run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 PyCodeObject *co;
1782 PyObject *v;
1783 co = PyAST_Compile(mod, filename, flags, arena);
1784 if (co == NULL)
1785 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001786 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 Py_DECREF(co);
1788 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001789}
1790
Guido van Rossum82598051997-03-05 00:20:32 +00001791static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001792run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 PyCodeObject *co;
1796 PyObject *v;
1797 long magic;
1798 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 magic = PyMarshal_ReadLongFromFile(fp);
1801 if (magic != PyImport_GetMagicNumber()) {
1802 PyErr_SetString(PyExc_RuntimeError,
1803 "Bad magic number in .pyc file");
1804 return NULL;
1805 }
1806 (void) PyMarshal_ReadLongFromFile(fp);
1807 v = PyMarshal_ReadLastObjectFromFile(fp);
1808 fclose(fp);
1809 if (v == NULL || !PyCode_Check(v)) {
1810 Py_XDECREF(v);
1811 PyErr_SetString(PyExc_RuntimeError,
1812 "Bad code object in .pyc file");
1813 return NULL;
1814 }
1815 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001816 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 if (v && flags)
1818 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1819 Py_DECREF(co);
1820 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001821}
1822
Guido van Rossum82598051997-03-05 00:20:32 +00001823PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001824Py_CompileStringExFlags(const char *str, const char *filename, int start,
1825 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 PyCodeObject *co;
1828 mod_ty mod;
1829 PyArena *arena = PyArena_New();
1830 if (arena == NULL)
1831 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1834 if (mod == NULL) {
1835 PyArena_Free(arena);
1836 return NULL;
1837 }
1838 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1839 PyObject *result = PyAST_mod2obj(mod);
1840 PyArena_Free(arena);
1841 return result;
1842 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001843 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 PyArena_Free(arena);
1845 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001846}
1847
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001848/* For use in Py_LIMITED_API */
1849#undef Py_CompileString
1850PyObject *
1851PyCompileString(const char *str, const char *filename, int start)
1852{
1853 return Py_CompileStringFlags(str, filename, start, NULL);
1854}
1855
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001856struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001857Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 struct symtable *st;
1860 mod_ty mod;
1861 PyCompilerFlags flags;
1862 PyArena *arena = PyArena_New();
1863 if (arena == NULL)
1864 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 flags.cf_flags = 0;
1867 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1868 if (mod == NULL) {
1869 PyArena_Free(arena);
1870 return NULL;
1871 }
1872 st = PySymtable_Build(mod, filename, 0);
1873 PyArena_Free(arena);
1874 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001875}
1876
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001877/* Preferred access to parser is through AST. */
1878mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001879PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 mod_ty mod;
1883 PyCompilerFlags localflags;
1884 perrdetail err;
1885 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1888 &_PyParser_Grammar, start, &err,
1889 &iflags);
1890 if (flags == NULL) {
1891 localflags.cf_flags = 0;
1892 flags = &localflags;
1893 }
1894 if (n) {
1895 flags->cf_flags |= iflags & PyCF_MASK;
1896 mod = PyAST_FromNode(n, flags, filename, arena);
1897 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 }
1899 else {
1900 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001901 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001903 err_free(&err);
1904 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905}
1906
1907mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001908PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 int start, char *ps1,
1910 char *ps2, PyCompilerFlags *flags, int *errcode,
1911 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 mod_ty mod;
1914 PyCompilerFlags localflags;
1915 perrdetail err;
1916 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1919 &_PyParser_Grammar,
1920 start, ps1, ps2, &err, &iflags);
1921 if (flags == NULL) {
1922 localflags.cf_flags = 0;
1923 flags = &localflags;
1924 }
1925 if (n) {
1926 flags->cf_flags |= iflags & PyCF_MASK;
1927 mod = PyAST_FromNode(n, flags, filename, arena);
1928 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 }
1930 else {
1931 err_input(&err);
1932 if (errcode)
1933 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02001934 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001936 err_free(&err);
1937 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001938}
1939
Guido van Rossuma110aa61994-08-29 12:50:44 +00001940/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001941
Guido van Rossuma110aa61994-08-29 12:50:44 +00001942node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001943PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 perrdetail err;
1946 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1947 &_PyParser_Grammar,
1948 start, NULL, NULL, &err, flags);
1949 if (n == NULL)
1950 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001951 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001954}
1955
Guido van Rossuma110aa61994-08-29 12:50:44 +00001956/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001957
Guido van Rossuma110aa61994-08-29 12:50:44 +00001958node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001959PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 perrdetail err;
1962 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1963 start, &err, flags);
1964 if (n == NULL)
1965 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001966 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001968}
1969
1970node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001971PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 perrdetail err;
1975 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1976 &_PyParser_Grammar, start, &err, flags);
1977 if (n == NULL)
1978 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001979 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001981}
1982
1983node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001984PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001987}
1988
Guido van Rossum66ebd912003-04-17 16:02:26 +00001989/* May want to move a more generalized form of this to parsetok.c or
1990 even parser modules. */
1991
1992void
Victor Stinner7f2fee32011-04-05 00:39:01 +02001993PyParser_ClearError(perrdetail *err)
1994{
1995 err_free(err);
1996}
1997
1998void
Guido van Rossum66ebd912003-04-17 16:02:26 +00001999PyParser_SetError(perrdetail *err)
2000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002002}
2003
Victor Stinner7f2fee32011-04-05 00:39:01 +02002004static void
2005err_free(perrdetail *err)
2006{
2007 Py_CLEAR(err->filename);
2008}
2009
Guido van Rossuma110aa61994-08-29 12:50:44 +00002010/* Set the error appropriate to the given input error code (see errcode.h) */
2011
2012static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002013err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 PyObject *v, *w, *errtype, *errtext;
2016 PyObject *msg_obj = NULL;
2017 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 errtype = PyExc_SyntaxError;
2020 switch (err->error) {
2021 case E_ERROR:
2022 return;
2023 case E_SYNTAX:
2024 errtype = PyExc_IndentationError;
2025 if (err->expected == INDENT)
2026 msg = "expected an indented block";
2027 else if (err->token == INDENT)
2028 msg = "unexpected indent";
2029 else if (err->token == DEDENT)
2030 msg = "unexpected unindent";
2031 else {
2032 errtype = PyExc_SyntaxError;
2033 msg = "invalid syntax";
2034 }
2035 break;
2036 case E_TOKEN:
2037 msg = "invalid token";
2038 break;
2039 case E_EOFS:
2040 msg = "EOF while scanning triple-quoted string literal";
2041 break;
2042 case E_EOLS:
2043 msg = "EOL while scanning string literal";
2044 break;
2045 case E_INTR:
2046 if (!PyErr_Occurred())
2047 PyErr_SetNone(PyExc_KeyboardInterrupt);
2048 goto cleanup;
2049 case E_NOMEM:
2050 PyErr_NoMemory();
2051 goto cleanup;
2052 case E_EOF:
2053 msg = "unexpected EOF while parsing";
2054 break;
2055 case E_TABSPACE:
2056 errtype = PyExc_TabError;
2057 msg = "inconsistent use of tabs and spaces in indentation";
2058 break;
2059 case E_OVERFLOW:
2060 msg = "expression too long";
2061 break;
2062 case E_DEDENT:
2063 errtype = PyExc_IndentationError;
2064 msg = "unindent does not match any outer indentation level";
2065 break;
2066 case E_TOODEEP:
2067 errtype = PyExc_IndentationError;
2068 msg = "too many levels of indentation";
2069 break;
2070 case E_DECODE: {
2071 PyObject *type, *value, *tb;
2072 PyErr_Fetch(&type, &value, &tb);
2073 msg = "unknown decode error";
2074 if (value != NULL)
2075 msg_obj = PyObject_Str(value);
2076 Py_XDECREF(type);
2077 Py_XDECREF(value);
2078 Py_XDECREF(tb);
2079 break;
2080 }
2081 case E_LINECONT:
2082 msg = "unexpected character after line continuation character";
2083 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 case E_IDENTIFIER:
2086 msg = "invalid character in identifier";
2087 break;
2088 default:
2089 fprintf(stderr, "error=%d\n", err->error);
2090 msg = "unknown parsing error";
2091 break;
2092 }
2093 /* err->text may not be UTF-8 in case of decoding errors.
2094 Explicitly convert to an object. */
2095 if (!err->text) {
2096 errtext = Py_None;
2097 Py_INCREF(Py_None);
2098 } else {
2099 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2100 "replace");
2101 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002102 v = Py_BuildValue("(OiiN)", err->filename,
2103 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (v != NULL) {
2105 if (msg_obj)
2106 w = Py_BuildValue("(OO)", msg_obj, v);
2107 else
2108 w = Py_BuildValue("(sO)", msg, v);
2109 } else
2110 w = NULL;
2111 Py_XDECREF(v);
2112 PyErr_SetObject(errtype, w);
2113 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002114cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 Py_XDECREF(msg_obj);
2116 if (err->text != NULL) {
2117 PyObject_FREE(err->text);
2118 err->text = NULL;
2119 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002120}
2121
2122/* Print fatal error message and abort */
2123
2124void
Tim Peters7c321a82002-07-09 02:57:01 +00002125Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002126{
Victor Stinner024e37a2011-03-31 01:31:06 +02002127 const int fd = fileno(stderr);
2128 PyThreadState *tstate;
2129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 fprintf(stderr, "Fatal Python error: %s\n", msg);
2131 fflush(stderr); /* it helps in Windows debug build */
2132 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002133 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002135 else {
2136 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2137 if (tstate != NULL) {
2138 fputc('\n', stderr);
2139 fflush(stderr);
2140 _Py_DumpTraceback(fd, tstate);
2141 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002142 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002143 }
2144
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002145#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 {
2147 size_t len = strlen(msg);
2148 WCHAR* buffer;
2149 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 /* Convert the message to wchar_t. This uses a simple one-to-one
2152 conversion, assuming that the this error message actually uses ASCII
2153 only. If this ceases to be true, we will have to convert. */
2154 buffer = alloca( (len+1) * (sizeof *buffer));
2155 for( i=0; i<=len; ++i)
2156 buffer[i] = msg[i];
2157 OutputDebugStringW(L"Fatal Python error: ");
2158 OutputDebugStringW(buffer);
2159 OutputDebugStringW(L"\n");
2160 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002161#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002163#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002164#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002166}
2167
2168/* Clean up and exit */
2169
Guido van Rossuma110aa61994-08-29 12:50:44 +00002170#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002171#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002172#endif
2173
Collin Winter670e6922007-03-21 02:57:17 +00002174static void (*pyexitfunc)(void) = NULL;
2175/* For the atexit module. */
2176void _Py_PyAtExit(void (*func)(void))
2177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002179}
2180
2181static void
2182call_py_exitfuncs(void)
2183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (pyexitfunc == NULL)
2185 return;
Collin Winter670e6922007-03-21 02:57:17 +00002186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 (*pyexitfunc)();
2188 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002189}
2190
Antoine Pitrou011bd622009-10-20 21:52:47 +00002191/* Wait until threading._shutdown completes, provided
2192 the threading module was imported in the first place.
2193 The shutdown routine will wait until all non-daemon
2194 "threading" threads have completed. */
2195static void
2196wait_for_thread_shutdown(void)
2197{
2198#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 PyObject *result;
2200 PyThreadState *tstate = PyThreadState_GET();
2201 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2202 "threading");
2203 if (threading == NULL) {
2204 /* threading not imported */
2205 PyErr_Clear();
2206 return;
2207 }
2208 result = PyObject_CallMethod(threading, "_shutdown", "");
2209 if (result == NULL) {
2210 PyErr_WriteUnraisable(threading);
2211 }
2212 else {
2213 Py_DECREF(result);
2214 }
2215 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002216#endif
2217}
2218
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002219#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002220static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002221static int nexitfuncs = 0;
2222
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002223int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 if (nexitfuncs >= NEXITFUNCS)
2226 return -1;
2227 exitfuncs[nexitfuncs++] = func;
2228 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002229}
2230
Guido van Rossumcc283f51997-08-05 02:22:03 +00002231static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002232call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 while (nexitfuncs > 0)
2235 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 fflush(stdout);
2238 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002239}
2240
2241void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002242Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002247}
2248
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002249static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002250initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002251{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002252#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002254#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002255#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002257#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002258#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002260#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002262}
2263
Guido van Rossum7433b121997-02-14 19:45:36 +00002264
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002265/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2266 *
2267 * All of the code in this function must only use async-signal-safe functions,
2268 * listed at `man 7 signal` or
2269 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2270 */
2271void
2272_Py_RestoreSignals(void)
2273{
2274#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002276#endif
2277#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002279#endif
2280#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002282#endif
2283}
2284
2285
Guido van Rossum7433b121997-02-14 19:45:36 +00002286/*
2287 * The file descriptor fd is considered ``interactive'' if either
2288 * a) isatty(fd) is TRUE, or
2289 * b) the -i flag was given, and the filename associated with
2290 * the descriptor is NULL or "<stdin>" or "???".
2291 */
2292int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002293Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 if (isatty((int)fileno(fp)))
2296 return 1;
2297 if (!Py_InteractiveFlag)
2298 return 0;
2299 return (filename == NULL) ||
2300 (strcmp(filename, "<stdin>") == 0) ||
2301 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002302}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002303
2304
Tim Petersd08e3822003-04-17 15:24:21 +00002305#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002306#if defined(WIN32) && defined(_MSC_VER)
2307
2308/* Stack checking for Microsoft C */
2309
2310#include <malloc.h>
2311#include <excpt.h>
2312
Fred Drakee8de31c2000-08-31 05:38:39 +00002313/*
2314 * Return non-zero when we run out of memory on the stack; zero otherwise.
2315 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002316int
Fred Drake399739f2000-08-31 05:52:44 +00002317PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 __try {
2320 /* alloca throws a stack overflow exception if there's
2321 not enough space left on the stack */
2322 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2323 return 0;
2324 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2325 EXCEPTION_EXECUTE_HANDLER :
2326 EXCEPTION_CONTINUE_SEARCH) {
2327 int errcode = _resetstkoflw();
2328 if (errcode == 0)
2329 {
2330 Py_FatalError("Could not reset the stack!");
2331 }
2332 }
2333 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002334}
2335
2336#endif /* WIN32 && _MSC_VER */
2337
2338/* Alternate implementations can be added here... */
2339
2340#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002341
2342
2343/* Wrappers around sigaction() or signal(). */
2344
2345PyOS_sighandler_t
2346PyOS_getsig(int sig)
2347{
2348#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 struct sigaction context;
2350 if (sigaction(sig, NULL, &context) == -1)
2351 return SIG_ERR;
2352 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002353#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002355/* Special signal handling for the secure CRT in Visual Studio 2005 */
2356#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 switch (sig) {
2358 /* Only these signals are valid */
2359 case SIGINT:
2360 case SIGILL:
2361 case SIGFPE:
2362 case SIGSEGV:
2363 case SIGTERM:
2364 case SIGBREAK:
2365 case SIGABRT:
2366 break;
2367 /* Don't call signal() with other values or it will assert */
2368 default:
2369 return SIG_ERR;
2370 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002371#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 handler = signal(sig, SIG_IGN);
2373 if (handler != SIG_ERR)
2374 signal(sig, handler);
2375 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002376#endif
2377}
2378
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002379/*
2380 * All of the code in this function must only use async-signal-safe functions,
2381 * listed at `man 7 signal` or
2382 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2383 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002384PyOS_sighandler_t
2385PyOS_setsig(int sig, PyOS_sighandler_t handler)
2386{
2387#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* Some code in Modules/signalmodule.c depends on sigaction() being
2389 * used here if HAVE_SIGACTION is defined. Fix that if this code
2390 * changes to invalidate that assumption.
2391 */
2392 struct sigaction context, ocontext;
2393 context.sa_handler = handler;
2394 sigemptyset(&context.sa_mask);
2395 context.sa_flags = 0;
2396 if (sigaction(sig, &context, &ocontext) == -1)
2397 return SIG_ERR;
2398 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002399#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 PyOS_sighandler_t oldhandler;
2401 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002402#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002404#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002406#endif
2407}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002408
2409/* Deprecated C API functions still provided for binary compatiblity */
2410
2411#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002412PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002416}
2417
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002418#undef PyParser_SimpleParseString
2419PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002420PyParser_SimpleParseString(const char *str, int start)
2421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002423}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002424
2425#undef PyRun_AnyFile
2426PyAPI_FUNC(int)
2427PyRun_AnyFile(FILE *fp, const char *name)
2428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002430}
2431
2432#undef PyRun_AnyFileEx
2433PyAPI_FUNC(int)
2434PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002437}
2438
2439#undef PyRun_AnyFileFlags
2440PyAPI_FUNC(int)
2441PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002444}
2445
2446#undef PyRun_File
2447PyAPI_FUNC(PyObject *)
2448PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002451}
2452
2453#undef PyRun_FileEx
2454PyAPI_FUNC(PyObject *)
2455PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002458}
2459
2460#undef PyRun_FileFlags
2461PyAPI_FUNC(PyObject *)
2462PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002466}
2467
2468#undef PyRun_SimpleFile
2469PyAPI_FUNC(int)
2470PyRun_SimpleFile(FILE *f, const char *p)
2471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002473}
2474
2475#undef PyRun_SimpleFileEx
2476PyAPI_FUNC(int)
2477PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002480}
2481
2482
2483#undef PyRun_String
2484PyAPI_FUNC(PyObject *)
2485PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002488}
2489
2490#undef PyRun_SimpleString
2491PyAPI_FUNC(int)
2492PyRun_SimpleString(const char *s)
2493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002495}
2496
2497#undef Py_CompileString
2498PyAPI_FUNC(PyObject *)
2499Py_CompileString(const char *str, const char *p, int s)
2500{
Georg Brandl8334fd92010-12-04 10:26:46 +00002501 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2502}
2503
2504#undef Py_CompileStringFlags
2505PyAPI_FUNC(PyObject *)
2506Py_CompileStringFlags(const char *str, const char *p, int s,
2507 PyCompilerFlags *flags)
2508{
2509 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002510}
2511
2512#undef PyRun_InteractiveOne
2513PyAPI_FUNC(int)
2514PyRun_InteractiveOne(FILE *f, const char *p)
2515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002517}
2518
2519#undef PyRun_InteractiveLoop
2520PyAPI_FUNC(int)
2521PyRun_InteractiveLoop(FILE *f, const char *p)
2522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002524}
2525
2526#ifdef __cplusplus
2527}
2528#endif