blob: a6787c4fc712f124906aad50adf249508ffba4ef [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 Stinnerb744ba12010-05-15 12:27:16 +000056static void initfsencoding(void);
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 Stinnerb744ba12010-05-15 12:27:16 +0000301 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (install_sigs)
304 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 initmain(); /* Module __main__ */
307 if (initstdio() < 0)
308 Py_FatalError(
309 "Py_Initialize: can't initialize sys standard streams");
310
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000311 /* Initialize warnings. */
312 if (PySys_HasWarnOptions()) {
313 PyObject *warnings_module = PyImport_ImportModule("warnings");
314 if (warnings_module == NULL) {
315 fprintf(stderr, "'import warnings' failed; traceback:\n");
316 PyErr_Print();
317 }
318 Py_XDECREF(warnings_module);
319 }
320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (!Py_NoSiteFlag)
322 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000323}
324
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000325void
326Py_Initialize(void)
327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000329}
330
331
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000332#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000333extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000334#endif
335
Guido van Rossume8432ac2007-07-09 15:04:50 +0000336/* Flush stdout and stderr */
337
Neal Norwitz2bad9702007-08-27 06:19:22 +0000338static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000339flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 PyObject *fout = PySys_GetObject("stdout");
342 PyObject *ferr = PySys_GetObject("stderr");
343 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 if (fout != NULL && fout != Py_None) {
346 tmp = PyObject_CallMethod(fout, "flush", "");
347 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000348 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 else
350 Py_DECREF(tmp);
351 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000352
Victor Stinner9467b212010-05-14 00:59:09 +0000353 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 tmp = PyObject_CallMethod(ferr, "flush", "");
355 if (tmp == NULL)
356 PyErr_Clear();
357 else
358 Py_DECREF(tmp);
359 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000360}
361
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362/* Undo the effect of Py_Initialize().
363
364 Beware: if multiple interpreter and/or thread states exist, these
365 are not wiped out; only the current thread and interpreter state
366 are deleted. But since everything else is deleted, those other
367 interpreter and thread states should no longer be used.
368
369 (XXX We should do better, e.g. wipe out all interpreters and
370 threads.)
371
372 Locking: as above.
373
374*/
375
376void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000377Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 PyInterpreterState *interp;
380 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (!initialized)
383 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 /* The interpreter is still entirely intact at this point, and the
388 * exit funcs may be relying on that. In particular, if some thread
389 * or exit func is still waiting to do an import, the import machinery
390 * expects Py_IsInitialized() to return true. So don't say the
391 * interpreter is uninitialized until after the exit funcs have run.
392 * Note that Threading.py uses an exit func to do a join on all the
393 * threads created thru it, so this also protects pending imports in
394 * the threads created via Threading.
395 */
396 call_py_exitfuncs();
397 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 /* Flush stdout+stderr */
400 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 /* Get current thread state and interpreter pointer */
403 tstate = PyThreadState_GET();
404 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 /* Disable signal handling */
407 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 /* Clear type lookup cache */
410 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 /* Collect garbage. This may call finalizers; it's nice to call these
413 * before all modules are destroyed.
414 * XXX If a __del__ or weakref callback is triggered here, and tries to
415 * XXX import a module, bad things can happen, because Python no
416 * XXX longer believes it's initialized.
417 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
418 * XXX is easy to provoke that way. I've also seen, e.g.,
419 * XXX Exception exceptions.ImportError: 'No module named sha'
420 * XXX in <function callback at 0x008F5718> ignored
421 * XXX but I'm unclear on exactly how that one happens. In any case,
422 * XXX I haven't seen a real-life report of either of these.
423 */
424 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000425#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 /* With COUNT_ALLOCS, it helps to run GC multiple times:
427 each collection might release some types from the type
428 list, so they become garbage. */
429 while (PyGC_Collect() > 0)
430 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000431#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000432 /* We run this while most interpreter state is still alive, so that
433 debug information can be printed out */
434 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 /* Destroy all modules */
437 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 /* Flush stdout+stderr (again, in case more was printed) */
440 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* Collect final garbage. This disposes of cycles created by
443 * new-style class definitions, for example.
444 * XXX This is disabled because it caused too many problems. If
445 * XXX a __del__ or weakref callback triggers here, Python code has
446 * XXX a hard time running, because even the sys module has been
447 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
448 * XXX One symptom is a sequence of information-free messages
449 * XXX coming from threads (if a __del__ or callback is invoked,
450 * XXX other threads can execute too, and any exception they encounter
451 * XXX triggers a comedy of errors as subsystem after subsystem
452 * XXX fails to find what it *expects* to find in sys to help report
453 * XXX the exception and consequent unexpected failures). I've also
454 * XXX seen segfaults then, after adding print statements to the
455 * XXX Python code getting called.
456 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000457#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000459#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
462 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000463
Victor Stinner024e37a2011-03-31 01:31:06 +0200464 /* unload faulthandler module */
465 _PyFaulthandler_Fini();
466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000468#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000470#endif
471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000473
Tim Peters9cf25ce2003-04-17 15:21:01 +0000474#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 /* Display all objects still alive -- this can invoke arbitrary
476 * __repr__ overrides, so requires a mostly-intact interpreter.
477 * Alas, a lot of stuff may still be alive now that will be cleaned
478 * up later.
479 */
480 if (Py_GETENV("PYTHONDUMPREFS"))
481 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000482#endif /* Py_TRACE_REFS */
483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* Clear interpreter state */
485 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 /* Now we decref the exception classes. After this point nothing
488 can raise an exception. That's okay, because each Fini() method
489 below has been checked to make sure no exceptions are ever
490 raised.
491 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000496#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000498#endif /* WITH_THREAD */
499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* Delete current thread */
501 PyThreadState_Swap(NULL);
502 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 /* Sundry finalizers */
505 PyMethod_Fini();
506 PyFrame_Fini();
507 PyCFunction_Fini();
508 PyTuple_Fini();
509 PyList_Fini();
510 PySet_Fini();
511 PyBytes_Fini();
512 PyByteArray_Fini();
513 PyLong_Fini();
514 PyFloat_Fini();
515 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* Cleanup Unicode implementation */
518 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000521 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 free((char*)Py_FileSystemDefaultEncoding);
523 Py_FileSystemDefaultEncoding = NULL;
524 }
Christian Heimesc8967002007-11-30 10:18:26 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* XXX Still allocated:
527 - various static ad-hoc pointers to interned strings
528 - int and float free list blocks
529 - whatever various modules and libraries allocate
530 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000533
Tim Peters269b2a62003-04-17 19:52:29 +0000534#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 /* Display addresses (& refcnts) of all objects still alive.
536 * An address can be used to find the repr of the object, printed
537 * above by _Py_PrintReferences.
538 */
539 if (Py_GETENV("PYTHONDUMPREFS"))
540 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000541#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000542#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 if (Py_GETENV("PYTHONMALLOCSTATS"))
544 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000545#endif
546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000548}
549
550/* Create and initialize a new interpreter and thread, and return the
551 new thread. This requires that Py_Initialize() has been called
552 first.
553
554 Unsuccessful initialization yields a NULL pointer. Note that *no*
555 exception information is available even in this case -- the
556 exception information is held in the thread, and there is no
557 thread.
558
559 Locking: as above.
560
561*/
562
563PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000564Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 PyInterpreterState *interp;
567 PyThreadState *tstate, *save_tstate;
568 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (!initialized)
571 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 interp = PyInterpreterState_New();
574 if (interp == NULL)
575 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 tstate = PyThreadState_New(interp);
578 if (tstate == NULL) {
579 PyInterpreterState_Delete(interp);
580 return NULL;
581 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 interp->modules = PyDict_New();
588 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589
Victor Stinner49d3f252010-10-17 01:24:53 +0000590 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 if (bimod != NULL) {
592 interp->builtins = PyModule_GetDict(bimod);
593 if (interp->builtins == NULL)
594 goto handle_error;
595 Py_INCREF(interp->builtins);
596 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 /* initialize builtin exceptions */
599 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000600
Victor Stinner49d3f252010-10-17 01:24:53 +0000601 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (bimod != NULL && sysmod != NULL) {
603 PyObject *pstderr;
604 interp->sysdict = PyModule_GetDict(sysmod);
605 if (interp->sysdict == NULL)
606 goto handle_error;
607 Py_INCREF(interp->sysdict);
608 PySys_SetPath(Py_GetPath());
609 PyDict_SetItemString(interp->sysdict, "modules",
610 interp->modules);
611 /* Set up a preliminary stderr printer until we have enough
612 infrastructure for the io module in place. */
613 pstderr = PyFile_NewStdPrinter(fileno(stderr));
614 if (pstderr == NULL)
615 Py_FatalError("Py_Initialize: can't set preliminary stderr");
616 PySys_SetObject("stderr", pstderr);
617 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000618 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 _PyImportHooks_Init();
621 if (initstdio() < 0)
622 Py_FatalError(
623 "Py_Initialize: can't initialize sys standard streams");
624 initmain();
625 if (!Py_NoSiteFlag)
626 initsite();
627 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (!PyErr_Occurred())
630 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631
Thomas Wouters89f507f2006-12-13 04:49:30 +0000632handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 PyErr_Print();
636 PyThreadState_Clear(tstate);
637 PyThreadState_Swap(save_tstate);
638 PyThreadState_Delete(tstate);
639 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000642}
643
644/* Delete an interpreter and its last thread. This requires that the
645 given thread state is current, that the thread has no remaining
646 frames, and that it is its interpreter's only remaining thread.
647 It is a fatal error to violate these constraints.
648
649 (Py_Finalize() doesn't have these constraints -- it zaps
650 everything, regardless.)
651
652 Locking: as above.
653
654*/
655
656void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000657Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (tstate != PyThreadState_GET())
662 Py_FatalError("Py_EndInterpreter: thread is not current");
663 if (tstate->frame != NULL)
664 Py_FatalError("Py_EndInterpreter: thread still has a frame");
665 if (tstate != interp->tstate_head || tstate->next != NULL)
666 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyImport_Cleanup();
669 PyInterpreterState_Clear(interp);
670 PyThreadState_Swap(NULL);
671 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000672}
673
Martin v. Löwis790465f2008-04-05 20:41:37 +0000674static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000675
676void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000677Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 if (pn && *pn)
680 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000681}
682
Martin v. Löwis790465f2008-04-05 20:41:37 +0000683wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000684Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000687}
688
Martin v. Löwis790465f2008-04-05 20:41:37 +0000689static wchar_t *default_home = NULL;
690static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000691
692void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000693Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000696}
697
Martin v. Löwis790465f2008-04-05 20:41:37 +0000698wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000699Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 wchar_t *home = default_home;
702 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
703 char* chome = Py_GETENV("PYTHONHOME");
704 if (chome) {
705 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
706 if (r != (size_t)-1 && r <= PATH_MAX)
707 home = env_home;
708 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 }
711 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000712}
713
Guido van Rossum6135a871995-01-09 17:53:26 +0000714/* Create __main__ module */
715
716static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000717initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyObject *m, *d;
720 m = PyImport_AddModule("__main__");
721 if (m == NULL)
722 Py_FatalError("can't create __main__ module");
723 d = PyModule_GetDict(m);
724 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
725 PyObject *bimod = PyImport_ImportModule("builtins");
726 if (bimod == NULL ||
727 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
728 Py_FatalError("can't add __builtins__ to __main__");
729 Py_DECREF(bimod);
730 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000731}
732
Victor Stinnerb744ba12010-05-15 12:27:16 +0000733static void
734initfsencoding(void)
735{
736 PyObject *codec;
737#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000738 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000739
Victor Stinner7f84ab52010-06-11 00:36:33 +0000740 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000741 /* On Unix, set the file system encoding according to the
742 user's preference, if the CODESET names a well-known
743 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000744 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000745 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000746 if (codeset == NULL)
747 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000748
Victor Stinnere4743092010-10-19 00:05:51 +0000749 Py_FileSystemDefaultEncoding = codeset;
750 Py_HasFileSystemDefaultEncoding = 0;
751 return;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000752 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000753#endif
754
755 /* the encoding is mbcs, utf-8 or ascii */
756 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
757 if (!codec) {
758 /* Such error can only occurs in critical situations: no more
759 * memory, import a module of the standard library failed,
760 * etc. */
761 Py_FatalError("Py_Initialize: unable to load the file system codec");
762 } else {
763 Py_DECREF(codec);
764 }
765}
766
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000767/* Import the site module (not into __main__ though) */
768
769static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000770initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 PyObject *m;
773 m = PyImport_ImportModule("site");
774 if (m == NULL) {
775 PyErr_Print();
776 Py_Finalize();
777 exit(1);
778 }
779 else {
780 Py_DECREF(m);
781 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000782}
783
Antoine Pitrou05608432009-01-09 18:53:14 +0000784static PyObject*
785create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 int fd, int write_mode, char* name,
787 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
790 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000791 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 PyObject *line_buffering;
793 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 /* stdin is always opened in buffered mode, first because it shouldn't
796 make a difference in common use cases, second because TextIOWrapper
797 depends on the presence of a read1() method which only exists on
798 buffered streams.
799 */
800 if (Py_UnbufferedStdioFlag && write_mode)
801 buffering = 0;
802 else
803 buffering = -1;
804 if (write_mode)
805 mode = "wb";
806 else
807 mode = "rb";
808 buf = PyObject_CallMethod(io, "open", "isiOOOi",
809 fd, mode, buffering,
810 Py_None, Py_None, Py_None, 0);
811 if (buf == NULL)
812 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (buffering) {
815 raw = PyObject_GetAttrString(buf, "raw");
816 if (raw == NULL)
817 goto error;
818 }
819 else {
820 raw = buf;
821 Py_INCREF(raw);
822 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 text = PyUnicode_FromString(name);
825 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
826 goto error;
827 res = PyObject_CallMethod(raw, "isatty", "");
828 if (res == NULL)
829 goto error;
830 isatty = PyObject_IsTrue(res);
831 Py_DECREF(res);
832 if (isatty == -1)
833 goto error;
834 if (isatty || Py_UnbufferedStdioFlag)
835 line_buffering = Py_True;
836 else
837 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 Py_CLEAR(raw);
840 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000841
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000842 newline = "\n";
843#ifdef MS_WINDOWS
844 if (!write_mode) {
845 /* translate \r\n to \n for sys.stdin on Windows */
846 newline = NULL;
847 }
848#endif
849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
851 buf, encoding, errors,
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000852 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 Py_CLEAR(buf);
854 if (stream == NULL)
855 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 if (write_mode)
858 mode = "w";
859 else
860 mode = "r";
861 text = PyUnicode_FromString(mode);
862 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
863 goto error;
864 Py_CLEAR(text);
865 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000866
867error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 Py_XDECREF(buf);
869 Py_XDECREF(stream);
870 Py_XDECREF(text);
871 Py_XDECREF(raw);
872 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000873}
874
Georg Brandl1a3284e2007-12-02 09:40:06 +0000875/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000876static int
877initstdio(void)
878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 PyObject *iomod = NULL, *wrapper;
880 PyObject *bimod = NULL;
881 PyObject *m;
882 PyObject *std = NULL;
883 int status = 0, fd;
884 PyObject * encoding_attr;
885 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 /* Hack to avoid a nasty recursion issue when Python is invoked
888 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
889 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
890 goto error;
891 }
892 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
895 goto error;
896 }
897 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (!(bimod = PyImport_ImportModule("builtins"))) {
900 goto error;
901 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 if (!(iomod = PyImport_ImportModule("io"))) {
904 goto error;
905 }
906 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
907 goto error;
908 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* Set builtins.open */
911 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000912 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 goto error;
914 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000915 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 encoding = Py_GETENV("PYTHONIOENCODING");
918 errors = NULL;
919 if (encoding) {
920 encoding = strdup(encoding);
921 errors = strchr(encoding, ':');
922 if (errors) {
923 *errors = '\0';
924 errors++;
925 }
926 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 /* Set sys.stdin */
929 fd = fileno(stdin);
930 /* Under some conditions stdin, stdout and stderr may not be connected
931 * and fileno() may point to an invalid file descriptor. For example
932 * GUI apps don't have valid standard streams by default.
933 */
934 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000935#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 std = Py_None;
937 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000938#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000940#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 }
942 else {
943 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
944 if (std == NULL)
945 goto error;
946 } /* if (fd < 0) */
947 PySys_SetObject("__stdin__", std);
948 PySys_SetObject("stdin", std);
949 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 /* Set sys.stdout */
952 fd = fileno(stdout);
953 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000954#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 std = Py_None;
956 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000957#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000959#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 }
961 else {
962 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
963 if (std == NULL)
964 goto error;
965 } /* if (fd < 0) */
966 PySys_SetObject("__stdout__", std);
967 PySys_SetObject("stdout", std);
968 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000969
Guido van Rossum98297ee2007-11-06 21:34:58 +0000970#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Set sys.stderr, replaces the preliminary stderr */
972 fd = fileno(stderr);
973 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000974#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 std = Py_None;
976 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000977#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000979#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 }
981 else {
982 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
983 if (std == NULL)
984 goto error;
985 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 /* Same as hack above, pre-import stderr's codec to avoid recursion
988 when import.c tries to write to stderr in verbose mode. */
989 encoding_attr = PyObject_GetAttrString(std, "encoding");
990 if (encoding_attr != NULL) {
991 const char * encoding;
992 encoding = _PyUnicode_AsString(encoding_attr);
993 if (encoding != NULL) {
994 _PyCodec_Lookup(encoding);
995 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000996 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 }
998 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PySys_SetObject("__stderr__", std);
1001 PySys_SetObject("stderr", std);
1002 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001003#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001006 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 status = -1;
1008 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 if (encoding)
1011 free(encoding);
1012 Py_XDECREF(bimod);
1013 Py_XDECREF(iomod);
1014 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001015}
1016
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001017/* Parse input from a file and execute it */
1018
1019int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001020PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (filename == NULL)
1024 filename = "???";
1025 if (Py_FdIsInteractive(fp, filename)) {
1026 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1027 if (closeit)
1028 fclose(fp);
1029 return err;
1030 }
1031 else
1032 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001033}
1034
1035int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001036PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyObject *v;
1039 int ret;
1040 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (flags == NULL) {
1043 flags = &local_flags;
1044 local_flags.cf_flags = 0;
1045 }
1046 v = PySys_GetObject("ps1");
1047 if (v == NULL) {
1048 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1049 Py_XDECREF(v);
1050 }
1051 v = PySys_GetObject("ps2");
1052 if (v == NULL) {
1053 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1054 Py_XDECREF(v);
1055 }
1056 for (;;) {
1057 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1058 PRINT_TOTAL_REFS();
1059 if (ret == E_EOF)
1060 return 0;
1061 /*
1062 if (ret == E_NOMEM)
1063 return -1;
1064 */
1065 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001066}
1067
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001068/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001069static int PARSER_FLAGS(PyCompilerFlags *flags)
1070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 int parser_flags = 0;
1072 if (!flags)
1073 return 0;
1074 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1075 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1076 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1077 parser_flags |= PyPARSE_IGNORE_COOKIE;
1078 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1079 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1080 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001081}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001082
Thomas Wouters89f507f2006-12-13 04:49:30 +00001083#if 0
1084/* Keep an example of flags with future keyword support. */
1085#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1087 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1088 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1089 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001090#endif
1091
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001092int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001093PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyObject *m, *d, *v, *w, *oenc = NULL;
1096 mod_ty mod;
1097 PyArena *arena;
1098 char *ps1 = "", *ps2 = "", *enc = NULL;
1099 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (fp == stdin) {
1102 /* Fetch encoding from sys.stdin */
1103 v = PySys_GetObject("stdin");
1104 if (v == NULL || v == Py_None)
1105 return -1;
1106 oenc = PyObject_GetAttrString(v, "encoding");
1107 if (!oenc)
1108 return -1;
1109 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001110 if (enc == NULL)
1111 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 }
1113 v = PySys_GetObject("ps1");
1114 if (v != NULL) {
1115 v = PyObject_Str(v);
1116 if (v == NULL)
1117 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001118 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001120 if (ps1 == NULL) {
1121 PyErr_Clear();
1122 ps1 = "";
1123 }
1124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 }
1126 w = PySys_GetObject("ps2");
1127 if (w != NULL) {
1128 w = PyObject_Str(w);
1129 if (w == NULL)
1130 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001131 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001133 if (ps2 == NULL) {
1134 PyErr_Clear();
1135 ps2 = "";
1136 }
1137 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 }
1139 arena = PyArena_New();
1140 if (arena == NULL) {
1141 Py_XDECREF(v);
1142 Py_XDECREF(w);
1143 Py_XDECREF(oenc);
1144 return -1;
1145 }
1146 mod = PyParser_ASTFromFile(fp, filename, enc,
1147 Py_single_input, ps1, ps2,
1148 flags, &errcode, arena);
1149 Py_XDECREF(v);
1150 Py_XDECREF(w);
1151 Py_XDECREF(oenc);
1152 if (mod == NULL) {
1153 PyArena_Free(arena);
1154 if (errcode == E_EOF) {
1155 PyErr_Clear();
1156 return E_EOF;
1157 }
1158 PyErr_Print();
1159 return -1;
1160 }
1161 m = PyImport_AddModule("__main__");
1162 if (m == NULL) {
1163 PyArena_Free(arena);
1164 return -1;
1165 }
1166 d = PyModule_GetDict(m);
1167 v = run_mod(mod, filename, d, d, flags, arena);
1168 PyArena_Free(arena);
1169 flush_io();
1170 if (v == NULL) {
1171 PyErr_Print();
1172 return -1;
1173 }
1174 Py_DECREF(v);
1175 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001176}
1177
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001178/* Check whether a file maybe a pyc file: Look at the extension,
1179 the file type, and, if we may close it, at the first few bytes. */
1180
1181static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001182maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1185 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 /* Only look into the file if we are allowed to close it, since
1188 it then should also be seekable. */
1189 if (closeit) {
1190 /* Read only two bytes of the magic. If the file was opened in
1191 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1192 be read as they are on disk. */
1193 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1194 unsigned char buf[2];
1195 /* Mess: In case of -x, the stream is NOT at its start now,
1196 and ungetc() was used to push back the first newline,
1197 which makes the current stream position formally undefined,
1198 and a x-platform nightmare.
1199 Unfortunately, we have no direct way to know whether -x
1200 was specified. So we use a terrible hack: if the current
1201 stream position is not 0, we assume -x was specified, and
1202 give up. Bug 132850 on SourceForge spells out the
1203 hopelessness of trying anything else (fseek and ftell
1204 don't work predictably x-platform for text-mode files).
1205 */
1206 int ispyc = 0;
1207 if (ftell(fp) == 0) {
1208 if (fread(buf, 1, 2, fp) == 2 &&
1209 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1210 ispyc = 1;
1211 rewind(fp);
1212 }
1213 return ispyc;
1214 }
1215 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001216}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001217
Guido van Rossum0df002c2000-08-27 19:21:52 +00001218int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001219PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 PyObject *m, *d, *v;
1223 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001224 int set_file_name = 0, ret;
1225 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 m = PyImport_AddModule("__main__");
1228 if (m == NULL)
1229 return -1;
1230 d = PyModule_GetDict(m);
1231 if (PyDict_GetItemString(d, "__file__") == NULL) {
1232 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001233 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (f == NULL)
1235 return -1;
1236 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1237 Py_DECREF(f);
1238 return -1;
1239 }
1240 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1241 return -1;
1242 set_file_name = 1;
1243 Py_DECREF(f);
1244 }
1245 len = strlen(filename);
1246 ext = filename + len - (len > 4 ? 4 : 0);
1247 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1248 /* Try to run a pyc file. First, re-open in binary */
1249 if (closeit)
1250 fclose(fp);
1251 if ((fp = fopen(filename, "rb")) == NULL) {
1252 fprintf(stderr, "python: Can't reopen .pyc file\n");
1253 ret = -1;
1254 goto done;
1255 }
1256 /* Turn on optimization if a .pyo file is given */
1257 if (strcmp(ext, ".pyo") == 0)
1258 Py_OptimizeFlag = 1;
1259 v = run_pyc_file(fp, filename, d, d, flags);
1260 } else {
1261 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1262 closeit, flags);
1263 }
1264 flush_io();
1265 if (v == NULL) {
1266 PyErr_Print();
1267 ret = -1;
1268 goto done;
1269 }
1270 Py_DECREF(v);
1271 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001272 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1274 PyErr_Clear();
1275 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001276}
1277
1278int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001279PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 PyObject *m, *d, *v;
1282 m = PyImport_AddModule("__main__");
1283 if (m == NULL)
1284 return -1;
1285 d = PyModule_GetDict(m);
1286 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1287 if (v == NULL) {
1288 PyErr_Print();
1289 return -1;
1290 }
1291 Py_DECREF(v);
1292 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001293}
1294
Barry Warsaw035574d1997-08-29 22:07:17 +00001295static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001296parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 long hold;
1300 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 /* old style errors */
1303 if (PyTuple_Check(err))
1304 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1305 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 if (! (v = PyObject_GetAttrString(err, "msg")))
1310 goto finally;
1311 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (!(v = PyObject_GetAttrString(err, "filename")))
1314 goto finally;
1315 if (v == Py_None)
1316 *filename = NULL;
1317 else if (! (*filename = _PyUnicode_AsString(v)))
1318 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 Py_DECREF(v);
1321 if (!(v = PyObject_GetAttrString(err, "lineno")))
1322 goto finally;
1323 hold = PyLong_AsLong(v);
1324 Py_DECREF(v);
1325 v = NULL;
1326 if (hold < 0 && PyErr_Occurred())
1327 goto finally;
1328 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 if (!(v = PyObject_GetAttrString(err, "offset")))
1331 goto finally;
1332 if (v == Py_None) {
1333 *offset = -1;
1334 Py_DECREF(v);
1335 v = NULL;
1336 } else {
1337 hold = PyLong_AsLong(v);
1338 Py_DECREF(v);
1339 v = NULL;
1340 if (hold < 0 && PyErr_Occurred())
1341 goto finally;
1342 *offset = (int)hold;
1343 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 if (!(v = PyObject_GetAttrString(err, "text")))
1346 goto finally;
1347 if (v == Py_None)
1348 *text = NULL;
1349 else if (!PyUnicode_Check(v) ||
1350 !(*text = _PyUnicode_AsString(v)))
1351 goto finally;
1352 Py_DECREF(v);
1353 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001354
1355finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 Py_XDECREF(v);
1357 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001358}
1359
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001360void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001361PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001364}
1365
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001366static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001367print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 char *nl;
1370 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001371 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1372 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 for (;;) {
1374 nl = strchr(text, '\n');
1375 if (nl == NULL || nl-text >= offset)
1376 break;
1377 offset -= (int)(nl+1-text);
1378 text = nl+1;
1379 }
1380 while (*text == ' ' || *text == '\t') {
1381 text++;
1382 offset--;
1383 }
1384 }
1385 PyFile_WriteString(" ", f);
1386 PyFile_WriteString(text, f);
1387 if (*text == '\0' || text[strlen(text)-1] != '\n')
1388 PyFile_WriteString("\n", f);
1389 if (offset == -1)
1390 return;
1391 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001392 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001395}
1396
Guido van Rossum66e8e862001-03-23 17:54:43 +00001397static void
1398handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 PyObject *exception, *value, *tb;
1401 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 if (Py_InspectFlag)
1404 /* Don't exit if -i flag was given. This flag is set to 0
1405 * when entering interactive mode for inspecting. */
1406 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 PyErr_Fetch(&exception, &value, &tb);
1409 fflush(stdout);
1410 if (value == NULL || value == Py_None)
1411 goto done;
1412 if (PyExceptionInstance_Check(value)) {
1413 /* The error code should be in the `code' attribute. */
1414 PyObject *code = PyObject_GetAttrString(value, "code");
1415 if (code) {
1416 Py_DECREF(value);
1417 value = code;
1418 if (value == Py_None)
1419 goto done;
1420 }
1421 /* If we failed to dig out the 'code' attribute,
1422 just let the else clause below print the error. */
1423 }
1424 if (PyLong_Check(value))
1425 exitcode = (int)PyLong_AsLong(value);
1426 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001427 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001428 if (sys_stderr != NULL && sys_stderr != Py_None) {
1429 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1430 } else {
1431 PyObject_Print(value, stderr, Py_PRINT_RAW);
1432 fflush(stderr);
1433 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 PySys_WriteStderr("\n");
1435 exitcode = 1;
1436 }
Tim Peterscf615b52003-04-19 18:47:02 +00001437 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 /* Restore and clear the exception info, in order to properly decref
1439 * the exception, value, and traceback. If we just exit instead,
1440 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1441 * some finalizers from running.
1442 */
1443 PyErr_Restore(exception, value, tb);
1444 PyErr_Clear();
1445 Py_Exit(exitcode);
1446 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001447}
1448
1449void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001450PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1455 handle_system_exit();
1456 }
1457 PyErr_Fetch(&exception, &v, &tb);
1458 if (exception == NULL)
1459 return;
1460 PyErr_NormalizeException(&exception, &v, &tb);
1461 if (tb == NULL) {
1462 tb = Py_None;
1463 Py_INCREF(tb);
1464 }
1465 PyException_SetTraceback(v, tb);
1466 if (exception == NULL)
1467 return;
1468 /* Now we know v != NULL too */
1469 if (set_sys_last_vars) {
1470 PySys_SetObject("last_type", exception);
1471 PySys_SetObject("last_value", v);
1472 PySys_SetObject("last_traceback", tb);
1473 }
1474 hook = PySys_GetObject("excepthook");
1475 if (hook) {
1476 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1477 PyObject *result = PyEval_CallObject(hook, args);
1478 if (result == NULL) {
1479 PyObject *exception2, *v2, *tb2;
1480 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1481 handle_system_exit();
1482 }
1483 PyErr_Fetch(&exception2, &v2, &tb2);
1484 PyErr_NormalizeException(&exception2, &v2, &tb2);
1485 /* It should not be possible for exception2 or v2
1486 to be NULL. However PyErr_Display() can't
1487 tolerate NULLs, so just be safe. */
1488 if (exception2 == NULL) {
1489 exception2 = Py_None;
1490 Py_INCREF(exception2);
1491 }
1492 if (v2 == NULL) {
1493 v2 = Py_None;
1494 Py_INCREF(v2);
1495 }
1496 fflush(stdout);
1497 PySys_WriteStderr("Error in sys.excepthook:\n");
1498 PyErr_Display(exception2, v2, tb2);
1499 PySys_WriteStderr("\nOriginal exception was:\n");
1500 PyErr_Display(exception, v, tb);
1501 Py_DECREF(exception2);
1502 Py_DECREF(v2);
1503 Py_XDECREF(tb2);
1504 }
1505 Py_XDECREF(result);
1506 Py_XDECREF(args);
1507 } else {
1508 PySys_WriteStderr("sys.excepthook is missing\n");
1509 PyErr_Display(exception, v, tb);
1510 }
1511 Py_XDECREF(exception);
1512 Py_XDECREF(v);
1513 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001514}
1515
Benjamin Petersone6528212008-07-15 15:32:09 +00001516static void
1517print_exception(PyObject *f, PyObject *value)
1518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 int err = 0;
1520 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (!PyExceptionInstance_Check(value)) {
1523 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1524 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1525 PyFile_WriteString(" found\n", f);
1526 return;
1527 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 Py_INCREF(value);
1530 fflush(stdout);
1531 type = (PyObject *) Py_TYPE(value);
1532 tb = PyException_GetTraceback(value);
1533 if (tb && tb != Py_None)
1534 err = PyTraceBack_Print(tb, f);
1535 if (err == 0 &&
1536 PyObject_HasAttrString(value, "print_file_and_line"))
1537 {
1538 PyObject *message;
1539 const char *filename, *text;
1540 int lineno, offset;
1541 if (!parse_syntax_error(value, &message, &filename,
1542 &lineno, &offset, &text))
1543 PyErr_Clear();
1544 else {
1545 char buf[10];
1546 PyFile_WriteString(" File \"", f);
1547 if (filename == NULL)
1548 PyFile_WriteString("<string>", f);
1549 else
1550 PyFile_WriteString(filename, f);
1551 PyFile_WriteString("\", line ", f);
1552 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1553 PyFile_WriteString(buf, f);
1554 PyFile_WriteString("\n", f);
1555 if (text != NULL)
1556 print_error_text(f, offset, text);
1557 Py_DECREF(value);
1558 value = message;
1559 /* Can't be bothered to check all those
1560 PyFile_WriteString() calls */
1561 if (PyErr_Occurred())
1562 err = -1;
1563 }
1564 }
1565 if (err) {
1566 /* Don't do anything else */
1567 }
1568 else {
1569 PyObject* moduleName;
1570 char* className;
1571 assert(PyExceptionClass_Check(type));
1572 className = PyExceptionClass_Name(type);
1573 if (className != NULL) {
1574 char *dot = strrchr(className, '.');
1575 if (dot != NULL)
1576 className = dot+1;
1577 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 moduleName = PyObject_GetAttrString(type, "__module__");
1580 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1581 {
1582 Py_DECREF(moduleName);
1583 err = PyFile_WriteString("<unknown>", f);
1584 }
1585 else {
1586 char* modstr = _PyUnicode_AsString(moduleName);
1587 if (modstr && strcmp(modstr, "builtins"))
1588 {
1589 err = PyFile_WriteString(modstr, f);
1590 err += PyFile_WriteString(".", f);
1591 }
1592 Py_DECREF(moduleName);
1593 }
1594 if (err == 0) {
1595 if (className == NULL)
1596 err = PyFile_WriteString("<unknown>", f);
1597 else
1598 err = PyFile_WriteString(className, f);
1599 }
1600 }
1601 if (err == 0 && (value != Py_None)) {
1602 PyObject *s = PyObject_Str(value);
1603 /* only print colon if the str() of the
1604 object is not the empty string
1605 */
1606 if (s == NULL)
1607 err = -1;
1608 else if (!PyUnicode_Check(s) ||
1609 PyUnicode_GetSize(s) != 0)
1610 err = PyFile_WriteString(": ", f);
1611 if (err == 0)
1612 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1613 Py_XDECREF(s);
1614 }
1615 /* try to write a newline in any case */
1616 err += PyFile_WriteString("\n", f);
1617 Py_XDECREF(tb);
1618 Py_DECREF(value);
1619 /* If an error happened here, don't show it.
1620 XXX This is wrong, but too many callers rely on this behavior. */
1621 if (err != 0)
1622 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001623}
1624
1625static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 "\nThe above exception was the direct cause "
1627 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001628
1629static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 "\nDuring handling of the above exception, "
1631 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001632
1633static void
1634print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 int err = 0, res;
1637 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (seen != NULL) {
1640 /* Exception chaining */
1641 if (PySet_Add(seen, value) == -1)
1642 PyErr_Clear();
1643 else if (PyExceptionInstance_Check(value)) {
1644 cause = PyException_GetCause(value);
1645 context = PyException_GetContext(value);
1646 if (cause) {
1647 res = PySet_Contains(seen, cause);
1648 if (res == -1)
1649 PyErr_Clear();
1650 if (res == 0) {
1651 print_exception_recursive(
1652 f, cause, seen);
1653 err |= PyFile_WriteString(
1654 cause_message, f);
1655 }
1656 }
1657 else if (context) {
1658 res = PySet_Contains(seen, context);
1659 if (res == -1)
1660 PyErr_Clear();
1661 if (res == 0) {
1662 print_exception_recursive(
1663 f, context, seen);
1664 err |= PyFile_WriteString(
1665 context_message, f);
1666 }
1667 }
1668 Py_XDECREF(context);
1669 Py_XDECREF(cause);
1670 }
1671 }
1672 print_exception(f, value);
1673 if (err != 0)
1674 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001675}
1676
Thomas Wouters477c8d52006-05-27 19:21:47 +00001677void
1678PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 PyObject *seen;
1681 PyObject *f = PySys_GetObject("stderr");
1682 if (f == Py_None) {
1683 /* pass */
1684 }
1685 else if (f == NULL) {
1686 _PyObject_Dump(value);
1687 fprintf(stderr, "lost sys.stderr\n");
1688 }
1689 else {
1690 /* We choose to ignore seen being possibly NULL, and report
1691 at least the main exception (it could be a MemoryError).
1692 */
1693 seen = PySet_New(NULL);
1694 if (seen == NULL)
1695 PyErr_Clear();
1696 print_exception_recursive(f, value, seen);
1697 Py_XDECREF(seen);
1698 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001699}
1700
Guido van Rossum82598051997-03-05 00:20:32 +00001701PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001702PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyObject *ret = NULL;
1706 mod_ty mod;
1707 PyArena *arena = PyArena_New();
1708 if (arena == NULL)
1709 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1712 if (mod != NULL)
1713 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1714 PyArena_Free(arena);
1715 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001716}
1717
1718PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001719PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 PyObject *ret;
1723 mod_ty mod;
1724 PyArena *arena = PyArena_New();
1725 if (arena == NULL)
1726 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1729 flags, NULL, arena);
1730 if (closeit)
1731 fclose(fp);
1732 if (mod == NULL) {
1733 PyArena_Free(arena);
1734 return NULL;
1735 }
1736 ret = run_mod(mod, filename, globals, locals, flags, arena);
1737 PyArena_Free(arena);
1738 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001739}
1740
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001741static void
1742flush_io(void)
1743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 PyObject *f, *r;
1745 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 /* Save the current exception */
1748 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 f = PySys_GetObject("stderr");
1751 if (f != NULL) {
1752 r = PyObject_CallMethod(f, "flush", "");
1753 if (r)
1754 Py_DECREF(r);
1755 else
1756 PyErr_Clear();
1757 }
1758 f = PySys_GetObject("stdout");
1759 if (f != NULL) {
1760 r = PyObject_CallMethod(f, "flush", "");
1761 if (r)
1762 Py_DECREF(r);
1763 else
1764 PyErr_Clear();
1765 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001768}
1769
Guido van Rossum82598051997-03-05 00:20:32 +00001770static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001771run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001773{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyCodeObject *co;
1775 PyObject *v;
1776 co = PyAST_Compile(mod, filename, flags, arena);
1777 if (co == NULL)
1778 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001779 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 Py_DECREF(co);
1781 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001782}
1783
Guido van Rossum82598051997-03-05 00:20:32 +00001784static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001785run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 PyCodeObject *co;
1789 PyObject *v;
1790 long magic;
1791 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 magic = PyMarshal_ReadLongFromFile(fp);
1794 if (magic != PyImport_GetMagicNumber()) {
1795 PyErr_SetString(PyExc_RuntimeError,
1796 "Bad magic number in .pyc file");
1797 return NULL;
1798 }
1799 (void) PyMarshal_ReadLongFromFile(fp);
1800 v = PyMarshal_ReadLastObjectFromFile(fp);
1801 fclose(fp);
1802 if (v == NULL || !PyCode_Check(v)) {
1803 Py_XDECREF(v);
1804 PyErr_SetString(PyExc_RuntimeError,
1805 "Bad code object in .pyc file");
1806 return NULL;
1807 }
1808 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001809 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 if (v && flags)
1811 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1812 Py_DECREF(co);
1813 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001814}
1815
Guido van Rossum82598051997-03-05 00:20:32 +00001816PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001817Py_CompileStringExFlags(const char *str, const char *filename, int start,
1818 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 PyCodeObject *co;
1821 mod_ty mod;
1822 PyArena *arena = PyArena_New();
1823 if (arena == NULL)
1824 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1827 if (mod == NULL) {
1828 PyArena_Free(arena);
1829 return NULL;
1830 }
1831 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1832 PyObject *result = PyAST_mod2obj(mod);
1833 PyArena_Free(arena);
1834 return result;
1835 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001836 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 PyArena_Free(arena);
1838 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001839}
1840
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001841/* For use in Py_LIMITED_API */
1842#undef Py_CompileString
1843PyObject *
1844PyCompileString(const char *str, const char *filename, int start)
1845{
1846 return Py_CompileStringFlags(str, filename, start, NULL);
1847}
1848
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001849struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001850Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 struct symtable *st;
1853 mod_ty mod;
1854 PyCompilerFlags flags;
1855 PyArena *arena = PyArena_New();
1856 if (arena == NULL)
1857 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 flags.cf_flags = 0;
1860 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1861 if (mod == NULL) {
1862 PyArena_Free(arena);
1863 return NULL;
1864 }
1865 st = PySymtable_Build(mod, filename, 0);
1866 PyArena_Free(arena);
1867 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001868}
1869
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001870/* Preferred access to parser is through AST. */
1871mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001872PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 mod_ty mod;
1876 PyCompilerFlags localflags;
1877 perrdetail err;
1878 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1881 &_PyParser_Grammar, start, &err,
1882 &iflags);
1883 if (flags == NULL) {
1884 localflags.cf_flags = 0;
1885 flags = &localflags;
1886 }
1887 if (n) {
1888 flags->cf_flags |= iflags & PyCF_MASK;
1889 mod = PyAST_FromNode(n, flags, filename, arena);
1890 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 }
1892 else {
1893 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001894 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001896 err_free(&err);
1897 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898}
1899
1900mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001901PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 int start, char *ps1,
1903 char *ps2, PyCompilerFlags *flags, int *errcode,
1904 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 mod_ty mod;
1907 PyCompilerFlags localflags;
1908 perrdetail err;
1909 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1912 &_PyParser_Grammar,
1913 start, ps1, ps2, &err, &iflags);
1914 if (flags == NULL) {
1915 localflags.cf_flags = 0;
1916 flags = &localflags;
1917 }
1918 if (n) {
1919 flags->cf_flags |= iflags & PyCF_MASK;
1920 mod = PyAST_FromNode(n, flags, filename, arena);
1921 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 }
1923 else {
1924 err_input(&err);
1925 if (errcode)
1926 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02001927 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001929 err_free(&err);
1930 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001931}
1932
Guido van Rossuma110aa61994-08-29 12:50:44 +00001933/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001934
Guido van Rossuma110aa61994-08-29 12:50:44 +00001935node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001936PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 perrdetail err;
1939 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1940 &_PyParser_Grammar,
1941 start, NULL, NULL, &err, flags);
1942 if (n == NULL)
1943 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001944 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001947}
1948
Guido van Rossuma110aa61994-08-29 12:50:44 +00001949/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001950
Guido van Rossuma110aa61994-08-29 12:50:44 +00001951node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001952PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 perrdetail err;
1955 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1956 start, &err, flags);
1957 if (n == NULL)
1958 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001959 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001961}
1962
1963node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001964PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 perrdetail err;
1968 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1969 &_PyParser_Grammar, start, &err, flags);
1970 if (n == NULL)
1971 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001972 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001974}
1975
1976node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001977PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001980}
1981
Guido van Rossum66ebd912003-04-17 16:02:26 +00001982/* May want to move a more generalized form of this to parsetok.c or
1983 even parser modules. */
1984
1985void
Victor Stinner7f2fee32011-04-05 00:39:01 +02001986PyParser_ClearError(perrdetail *err)
1987{
1988 err_free(err);
1989}
1990
1991void
Guido van Rossum66ebd912003-04-17 16:02:26 +00001992PyParser_SetError(perrdetail *err)
1993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001995}
1996
Victor Stinner7f2fee32011-04-05 00:39:01 +02001997static void
1998err_free(perrdetail *err)
1999{
2000 Py_CLEAR(err->filename);
2001}
2002
Guido van Rossuma110aa61994-08-29 12:50:44 +00002003/* Set the error appropriate to the given input error code (see errcode.h) */
2004
2005static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002006err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 PyObject *v, *w, *errtype, *errtext;
2009 PyObject *msg_obj = NULL;
2010 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 errtype = PyExc_SyntaxError;
2013 switch (err->error) {
2014 case E_ERROR:
2015 return;
2016 case E_SYNTAX:
2017 errtype = PyExc_IndentationError;
2018 if (err->expected == INDENT)
2019 msg = "expected an indented block";
2020 else if (err->token == INDENT)
2021 msg = "unexpected indent";
2022 else if (err->token == DEDENT)
2023 msg = "unexpected unindent";
2024 else {
2025 errtype = PyExc_SyntaxError;
2026 msg = "invalid syntax";
2027 }
2028 break;
2029 case E_TOKEN:
2030 msg = "invalid token";
2031 break;
2032 case E_EOFS:
2033 msg = "EOF while scanning triple-quoted string literal";
2034 break;
2035 case E_EOLS:
2036 msg = "EOL while scanning string literal";
2037 break;
2038 case E_INTR:
2039 if (!PyErr_Occurred())
2040 PyErr_SetNone(PyExc_KeyboardInterrupt);
2041 goto cleanup;
2042 case E_NOMEM:
2043 PyErr_NoMemory();
2044 goto cleanup;
2045 case E_EOF:
2046 msg = "unexpected EOF while parsing";
2047 break;
2048 case E_TABSPACE:
2049 errtype = PyExc_TabError;
2050 msg = "inconsistent use of tabs and spaces in indentation";
2051 break;
2052 case E_OVERFLOW:
2053 msg = "expression too long";
2054 break;
2055 case E_DEDENT:
2056 errtype = PyExc_IndentationError;
2057 msg = "unindent does not match any outer indentation level";
2058 break;
2059 case E_TOODEEP:
2060 errtype = PyExc_IndentationError;
2061 msg = "too many levels of indentation";
2062 break;
2063 case E_DECODE: {
2064 PyObject *type, *value, *tb;
2065 PyErr_Fetch(&type, &value, &tb);
2066 msg = "unknown decode error";
2067 if (value != NULL)
2068 msg_obj = PyObject_Str(value);
2069 Py_XDECREF(type);
2070 Py_XDECREF(value);
2071 Py_XDECREF(tb);
2072 break;
2073 }
2074 case E_LINECONT:
2075 msg = "unexpected character after line continuation character";
2076 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 case E_IDENTIFIER:
2079 msg = "invalid character in identifier";
2080 break;
2081 default:
2082 fprintf(stderr, "error=%d\n", err->error);
2083 msg = "unknown parsing error";
2084 break;
2085 }
2086 /* err->text may not be UTF-8 in case of decoding errors.
2087 Explicitly convert to an object. */
2088 if (!err->text) {
2089 errtext = Py_None;
2090 Py_INCREF(Py_None);
2091 } else {
2092 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2093 "replace");
2094 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002095 v = Py_BuildValue("(OiiN)", err->filename,
2096 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 if (v != NULL) {
2098 if (msg_obj)
2099 w = Py_BuildValue("(OO)", msg_obj, v);
2100 else
2101 w = Py_BuildValue("(sO)", msg, v);
2102 } else
2103 w = NULL;
2104 Py_XDECREF(v);
2105 PyErr_SetObject(errtype, w);
2106 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002107cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 Py_XDECREF(msg_obj);
2109 if (err->text != NULL) {
2110 PyObject_FREE(err->text);
2111 err->text = NULL;
2112 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002113}
2114
2115/* Print fatal error message and abort */
2116
2117void
Tim Peters7c321a82002-07-09 02:57:01 +00002118Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002119{
Victor Stinner024e37a2011-03-31 01:31:06 +02002120 const int fd = fileno(stderr);
2121 PyThreadState *tstate;
2122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 fprintf(stderr, "Fatal Python error: %s\n", msg);
2124 fflush(stderr); /* it helps in Windows debug build */
2125 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002126 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002128 else {
2129 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2130 if (tstate != NULL) {
2131 fputc('\n', stderr);
2132 fflush(stderr);
2133 _Py_DumpTraceback(fd, tstate);
2134 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002135 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002136 }
2137
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002138#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 {
2140 size_t len = strlen(msg);
2141 WCHAR* buffer;
2142 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 /* Convert the message to wchar_t. This uses a simple one-to-one
2145 conversion, assuming that the this error message actually uses ASCII
2146 only. If this ceases to be true, we will have to convert. */
2147 buffer = alloca( (len+1) * (sizeof *buffer));
2148 for( i=0; i<=len; ++i)
2149 buffer[i] = msg[i];
2150 OutputDebugStringW(L"Fatal Python error: ");
2151 OutputDebugStringW(buffer);
2152 OutputDebugStringW(L"\n");
2153 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002154#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002156#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002157#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002159}
2160
2161/* Clean up and exit */
2162
Guido van Rossuma110aa61994-08-29 12:50:44 +00002163#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002164#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002165#endif
2166
Collin Winter670e6922007-03-21 02:57:17 +00002167static void (*pyexitfunc)(void) = NULL;
2168/* For the atexit module. */
2169void _Py_PyAtExit(void (*func)(void))
2170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002172}
2173
2174static void
2175call_py_exitfuncs(void)
2176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 if (pyexitfunc == NULL)
2178 return;
Collin Winter670e6922007-03-21 02:57:17 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 (*pyexitfunc)();
2181 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002182}
2183
Antoine Pitrou011bd622009-10-20 21:52:47 +00002184/* Wait until threading._shutdown completes, provided
2185 the threading module was imported in the first place.
2186 The shutdown routine will wait until all non-daemon
2187 "threading" threads have completed. */
2188static void
2189wait_for_thread_shutdown(void)
2190{
2191#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 PyObject *result;
2193 PyThreadState *tstate = PyThreadState_GET();
2194 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2195 "threading");
2196 if (threading == NULL) {
2197 /* threading not imported */
2198 PyErr_Clear();
2199 return;
2200 }
2201 result = PyObject_CallMethod(threading, "_shutdown", "");
2202 if (result == NULL) {
2203 PyErr_WriteUnraisable(threading);
2204 }
2205 else {
2206 Py_DECREF(result);
2207 }
2208 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002209#endif
2210}
2211
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002212#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002213static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002214static int nexitfuncs = 0;
2215
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002216int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 if (nexitfuncs >= NEXITFUNCS)
2219 return -1;
2220 exitfuncs[nexitfuncs++] = func;
2221 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002222}
2223
Guido van Rossumcc283f51997-08-05 02:22:03 +00002224static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002225call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 while (nexitfuncs > 0)
2228 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 fflush(stdout);
2231 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002232}
2233
2234void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002235Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002240}
2241
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002242static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002243initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002244{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002245#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002247#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002248#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002250#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002251#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002253#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002255}
2256
Guido van Rossum7433b121997-02-14 19:45:36 +00002257
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002258/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2259 *
2260 * All of the code in this function must only use async-signal-safe functions,
2261 * listed at `man 7 signal` or
2262 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2263 */
2264void
2265_Py_RestoreSignals(void)
2266{
2267#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002269#endif
2270#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002272#endif
2273#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002275#endif
2276}
2277
2278
Guido van Rossum7433b121997-02-14 19:45:36 +00002279/*
2280 * The file descriptor fd is considered ``interactive'' if either
2281 * a) isatty(fd) is TRUE, or
2282 * b) the -i flag was given, and the filename associated with
2283 * the descriptor is NULL or "<stdin>" or "???".
2284 */
2285int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002286Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 if (isatty((int)fileno(fp)))
2289 return 1;
2290 if (!Py_InteractiveFlag)
2291 return 0;
2292 return (filename == NULL) ||
2293 (strcmp(filename, "<stdin>") == 0) ||
2294 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002295}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002296
2297
Tim Petersd08e3822003-04-17 15:24:21 +00002298#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002299#if defined(WIN32) && defined(_MSC_VER)
2300
2301/* Stack checking for Microsoft C */
2302
2303#include <malloc.h>
2304#include <excpt.h>
2305
Fred Drakee8de31c2000-08-31 05:38:39 +00002306/*
2307 * Return non-zero when we run out of memory on the stack; zero otherwise.
2308 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002309int
Fred Drake399739f2000-08-31 05:52:44 +00002310PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 __try {
2313 /* alloca throws a stack overflow exception if there's
2314 not enough space left on the stack */
2315 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2316 return 0;
2317 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2318 EXCEPTION_EXECUTE_HANDLER :
2319 EXCEPTION_CONTINUE_SEARCH) {
2320 int errcode = _resetstkoflw();
2321 if (errcode == 0)
2322 {
2323 Py_FatalError("Could not reset the stack!");
2324 }
2325 }
2326 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002327}
2328
2329#endif /* WIN32 && _MSC_VER */
2330
2331/* Alternate implementations can be added here... */
2332
2333#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002334
2335
2336/* Wrappers around sigaction() or signal(). */
2337
2338PyOS_sighandler_t
2339PyOS_getsig(int sig)
2340{
2341#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 struct sigaction context;
2343 if (sigaction(sig, NULL, &context) == -1)
2344 return SIG_ERR;
2345 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002346#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002348/* Special signal handling for the secure CRT in Visual Studio 2005 */
2349#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 switch (sig) {
2351 /* Only these signals are valid */
2352 case SIGINT:
2353 case SIGILL:
2354 case SIGFPE:
2355 case SIGSEGV:
2356 case SIGTERM:
2357 case SIGBREAK:
2358 case SIGABRT:
2359 break;
2360 /* Don't call signal() with other values or it will assert */
2361 default:
2362 return SIG_ERR;
2363 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002364#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 handler = signal(sig, SIG_IGN);
2366 if (handler != SIG_ERR)
2367 signal(sig, handler);
2368 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002369#endif
2370}
2371
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002372/*
2373 * All of the code in this function must only use async-signal-safe functions,
2374 * listed at `man 7 signal` or
2375 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2376 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002377PyOS_sighandler_t
2378PyOS_setsig(int sig, PyOS_sighandler_t handler)
2379{
2380#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* Some code in Modules/signalmodule.c depends on sigaction() being
2382 * used here if HAVE_SIGACTION is defined. Fix that if this code
2383 * changes to invalidate that assumption.
2384 */
2385 struct sigaction context, ocontext;
2386 context.sa_handler = handler;
2387 sigemptyset(&context.sa_mask);
2388 context.sa_flags = 0;
2389 if (sigaction(sig, &context, &ocontext) == -1)
2390 return SIG_ERR;
2391 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002392#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 PyOS_sighandler_t oldhandler;
2394 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002395#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002397#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002399#endif
2400}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002401
2402/* Deprecated C API functions still provided for binary compatiblity */
2403
2404#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002405PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002406PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002409}
2410
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002411#undef PyParser_SimpleParseString
2412PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002413PyParser_SimpleParseString(const char *str, int start)
2414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002416}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002417
2418#undef PyRun_AnyFile
2419PyAPI_FUNC(int)
2420PyRun_AnyFile(FILE *fp, const char *name)
2421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002423}
2424
2425#undef PyRun_AnyFileEx
2426PyAPI_FUNC(int)
2427PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002430}
2431
2432#undef PyRun_AnyFileFlags
2433PyAPI_FUNC(int)
2434PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002437}
2438
2439#undef PyRun_File
2440PyAPI_FUNC(PyObject *)
2441PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002444}
2445
2446#undef PyRun_FileEx
2447PyAPI_FUNC(PyObject *)
2448PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002451}
2452
2453#undef PyRun_FileFlags
2454PyAPI_FUNC(PyObject *)
2455PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002459}
2460
2461#undef PyRun_SimpleFile
2462PyAPI_FUNC(int)
2463PyRun_SimpleFile(FILE *f, const char *p)
2464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002466}
2467
2468#undef PyRun_SimpleFileEx
2469PyAPI_FUNC(int)
2470PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002473}
2474
2475
2476#undef PyRun_String
2477PyAPI_FUNC(PyObject *)
2478PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002481}
2482
2483#undef PyRun_SimpleString
2484PyAPI_FUNC(int)
2485PyRun_SimpleString(const char *s)
2486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002488}
2489
2490#undef Py_CompileString
2491PyAPI_FUNC(PyObject *)
2492Py_CompileString(const char *str, const char *p, int s)
2493{
Georg Brandl8334fd92010-12-04 10:26:46 +00002494 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2495}
2496
2497#undef Py_CompileStringFlags
2498PyAPI_FUNC(PyObject *)
2499Py_CompileStringFlags(const char *str, const char *p, int s,
2500 PyCompilerFlags *flags)
2501{
2502 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002503}
2504
2505#undef PyRun_InteractiveOne
2506PyAPI_FUNC(int)
2507PyRun_InteractiveOne(FILE *f, const char *p)
2508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002510}
2511
2512#undef PyRun_InteractiveLoop
2513PyAPI_FUNC(int)
2514PyRun_InteractiveLoop(FILE *f, const char *p)
2515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002517}
2518
2519#ifdef __cplusplus
2520}
2521#endif