blob: 232d7befa02f6729d52ec429b08c3e7cb3fc3edc [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
43 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#endif
45
46#ifdef __cplusplus
47extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000048#endif
49
Martin v. Löwis790465f2008-04-05 20:41:37 +000050extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000051
Guido van Rossum82598051997-03-05 00:20:32 +000052extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossumb73cc041993-11-01 16:28:59 +000054/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static void initmain(void);
Victor Stinner793b5312011-04-27 00:24:21 +020056static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020065static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000067static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000068static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000069static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000070extern void _PyUnicode_Init(void);
71extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020074extern int _PyFaulthandler_Init(void);
75extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000084int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000085int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020086int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
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
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020096PyThreadState *_Py_Finalizing = NULL;
97
Christian Heimes33fe8092008-04-13 13:53:33 +000098/* PyModule_GetWarningsModule is no longer necessary as of 2.6
99since _warnings is builtin. This API should not be used. */
100PyObject *
101PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000104}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000105
Guido van Rossum25ce5661997-08-02 03:10:38 +0000106static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000107
Thomas Wouters7e474022000-07-16 12:04:32 +0000108/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109
110int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000111Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000114}
115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116/* Global initializations. Can be undone by Py_Finalize(). Don't
117 call this twice without an intervening Py_Finalize() call. When
118 initializations fail, a fatal error is issued and the function does
119 not return. On return, the first thread and interpreter state have
120 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000121
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122 Locking: you must hold the interpreter lock while calling this.
123 (If the lock has not yet been initialized, that's equivalent to
124 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000125
Guido van Rossum25ce5661997-08-02 03:10:38 +0000126*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000127
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000128static int
129add_flag(int flag, const char *envs)
130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000131 int env = atoi(envs);
132 if (flag < env)
133 flag = env;
134 if (flag < 1)
135 flag = 1;
136 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000137}
138
Christian Heimes5833a2f2008-10-30 21:40:04 +0000139static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000140get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000141{
Victor Stinner94908bb2010-08-18 21:23:25 +0000142 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000143 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000144
Victor Stinner94908bb2010-08-18 21:23:25 +0000145 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 if (!codec)
147 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 name = PyObject_GetAttrString(codec, "name");
150 Py_CLEAR(codec);
151 if (!name)
152 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000153
Victor Stinner94908bb2010-08-18 21:23:25 +0000154 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100155 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000156 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000157 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000159 if (name_str == NULL) {
160 PyErr_NoMemory();
161 return NULL;
162 }
163 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000164
165error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000167 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000169}
Victor Stinner94908bb2010-08-18 21:23:25 +0000170
171#if defined(HAVE_LANGINFO_H) && defined(CODESET)
172static char*
173get_codeset(void)
174{
175 char* codeset = nl_langinfo(CODESET);
176 if (!codeset || codeset[0] == '\0') {
177 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
178 return NULL;
179 }
180 return get_codec_name(codeset);
181}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000182#endif
183
Guido van Rossuma027efa1997-05-05 20:56:21 +0000184void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000185Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 PyInterpreterState *interp;
188 PyThreadState *tstate;
189 PyObject *bimod, *sysmod, *pstderr;
190 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 if (initialized)
194 return;
195 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200196 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000197
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000198#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 /* Set up the LC_CTYPE locale, so we can obtain
200 the locale's charset without having to switch
201 locales. */
202 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000203#endif
204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
206 Py_DebugFlag = add_flag(Py_DebugFlag, p);
207 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
208 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
209 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
210 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
211 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
212 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 interp = PyInterpreterState_New();
215 if (interp == NULL)
216 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 tstate = PyThreadState_New(interp);
219 if (tstate == NULL)
220 Py_FatalError("Py_Initialize: can't make first thread");
221 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000222
Victor Stinner6961bd62010-08-17 22:26:51 +0000223#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000224 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
225 destroying the GIL might fail when it is being referenced from
226 another running thread (see issue #9901).
227 Instead we destroy the previously created GIL here, which ensures
228 that we can call Py_Initialize / Py_Finalize multiple times. */
229 _PyEval_FiniThreads();
230
231 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000232 _PyGILState_Init(interp, tstate);
233#endif /* WITH_THREAD */
234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (!_PyFrame_Init())
238 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (!_PyLong_Init())
241 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 if (!PyByteArray_Init())
244 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 interp->modules = PyDict_New();
249 if (interp->modules == NULL)
250 Py_FatalError("Py_Initialize: can't make modules dictionary");
251 interp->modules_reloading = PyDict_New();
252 if (interp->modules_reloading == NULL)
253 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 /* Init Unicode implementation; relies on the codec registry */
256 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 bimod = _PyBuiltin_Init();
259 if (bimod == NULL)
260 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000261 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 interp->builtins = PyModule_GetDict(bimod);
263 if (interp->builtins == NULL)
264 Py_FatalError("Py_Initialize: can't initialize builtins dict");
265 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 /* initialize builtin exceptions */
268 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 sysmod = _PySys_Init();
271 if (sysmod == NULL)
272 Py_FatalError("Py_Initialize: can't initialize sys");
273 interp->sysdict = PyModule_GetDict(sysmod);
274 if (interp->sysdict == NULL)
275 Py_FatalError("Py_Initialize: can't initialize sys dict");
276 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000277 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 PySys_SetPath(Py_GetPath());
279 PyDict_SetItemString(interp->sysdict, "modules",
280 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 /* Set up a preliminary stderr printer until we have enough
283 infrastructure for the io module in place. */
284 pstderr = PyFile_NewStdPrinter(fileno(stderr));
285 if (pstderr == NULL)
286 Py_FatalError("Py_Initialize: can't set preliminary stderr");
287 PySys_SetObject("stderr", pstderr);
288 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000289 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000294
Victor Stinner024e37a2011-03-31 01:31:06 +0200295 /* initialize the faulthandler module */
296 if (_PyFaulthandler_Init())
297 Py_FatalError("Py_Initialize: can't initialize faulthandler");
298
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000299 /* Initialize _warnings. */
300 _PyWarnings_Init();
301
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000302 _PyTime_Init();
303
Victor Stinner793b5312011-04-27 00:24:21 +0200304 if (initfsencoding(interp) < 0)
305 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (install_sigs)
308 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 initmain(); /* Module __main__ */
311 if (initstdio() < 0)
312 Py_FatalError(
313 "Py_Initialize: can't initialize sys standard streams");
314
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000315 /* Initialize warnings. */
316 if (PySys_HasWarnOptions()) {
317 PyObject *warnings_module = PyImport_ImportModule("warnings");
318 if (warnings_module == NULL) {
319 fprintf(stderr, "'import warnings' failed; traceback:\n");
320 PyErr_Print();
321 }
322 Py_XDECREF(warnings_module);
323 }
324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (!Py_NoSiteFlag)
326 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000327}
328
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000329void
330Py_Initialize(void)
331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000333}
334
335
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000336#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000337extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000338#endif
339
Guido van Rossume8432ac2007-07-09 15:04:50 +0000340/* Flush stdout and stderr */
341
Neal Norwitz2bad9702007-08-27 06:19:22 +0000342static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000343flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 PyObject *fout = PySys_GetObject("stdout");
346 PyObject *ferr = PySys_GetObject("stderr");
347 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 if (fout != NULL && fout != Py_None) {
350 tmp = PyObject_CallMethod(fout, "flush", "");
351 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000352 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 else
354 Py_DECREF(tmp);
355 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000356
Victor Stinner9467b212010-05-14 00:59:09 +0000357 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 tmp = PyObject_CallMethod(ferr, "flush", "");
359 if (tmp == NULL)
360 PyErr_Clear();
361 else
362 Py_DECREF(tmp);
363 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000364}
365
Guido van Rossum25ce5661997-08-02 03:10:38 +0000366/* Undo the effect of Py_Initialize().
367
368 Beware: if multiple interpreter and/or thread states exist, these
369 are not wiped out; only the current thread and interpreter state
370 are deleted. But since everything else is deleted, those other
371 interpreter and thread states should no longer be used.
372
373 (XXX We should do better, e.g. wipe out all interpreters and
374 threads.)
375
376 Locking: as above.
377
378*/
379
380void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000381Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyInterpreterState *interp;
384 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (!initialized)
387 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 /* The interpreter is still entirely intact at this point, and the
392 * exit funcs may be relying on that. In particular, if some thread
393 * or exit func is still waiting to do an import, the import machinery
394 * expects Py_IsInitialized() to return true. So don't say the
395 * interpreter is uninitialized until after the exit funcs have run.
396 * Note that Threading.py uses an exit func to do a join on all the
397 * threads created thru it, so this also protects pending imports in
398 * the threads created via Threading.
399 */
400 call_py_exitfuncs();
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 Pitrou0d5e52d2011-05-04 20:02:30 +0200406 /* Remaining threads (e.g. daemon threads) will automatically exit
407 after taking the GIL (in PyEval_RestoreThread()). */
408 _Py_Finalizing = tstate;
409 initialized = 0;
410
411 /* Flush stdout+stderr */
412 flush_std_files();
413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 /* Disable signal handling */
415 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 /* Clear type lookup cache */
418 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 /* Collect garbage. This may call finalizers; it's nice to call these
421 * before all modules are destroyed.
422 * XXX If a __del__ or weakref callback is triggered here, and tries to
423 * XXX import a module, bad things can happen, because Python no
424 * XXX longer believes it's initialized.
425 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
426 * XXX is easy to provoke that way. I've also seen, e.g.,
427 * XXX Exception exceptions.ImportError: 'No module named sha'
428 * XXX in <function callback at 0x008F5718> ignored
429 * XXX but I'm unclear on exactly how that one happens. In any case,
430 * XXX I haven't seen a real-life report of either of these.
431 */
432 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000433#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 /* With COUNT_ALLOCS, it helps to run GC multiple times:
435 each collection might release some types from the type
436 list, so they become garbage. */
437 while (PyGC_Collect() > 0)
438 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000439#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000440 /* We run this while most interpreter state is still alive, so that
441 debug information can be printed out */
442 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 /* Destroy all modules */
445 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 /* Flush stdout+stderr (again, in case more was printed) */
448 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 /* Collect final garbage. This disposes of cycles created by
451 * new-style class definitions, for example.
452 * XXX This is disabled because it caused too many problems. If
453 * XXX a __del__ or weakref callback triggers here, Python code has
454 * XXX a hard time running, because even the sys module has been
455 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
456 * XXX One symptom is a sequence of information-free messages
457 * XXX coming from threads (if a __del__ or callback is invoked,
458 * XXX other threads can execute too, and any exception they encounter
459 * XXX triggers a comedy of errors as subsystem after subsystem
460 * XXX fails to find what it *expects* to find in sys to help report
461 * XXX the exception and consequent unexpected failures). I've also
462 * XXX seen segfaults then, after adding print statements to the
463 * XXX Python code getting called.
464 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000465#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000467#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
470 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000471
Victor Stinner024e37a2011-03-31 01:31:06 +0200472 /* unload faulthandler module */
473 _PyFaulthandler_Fini();
474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000476#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000478#endif
479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000481
Tim Peters9cf25ce2003-04-17 15:21:01 +0000482#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 /* Display all objects still alive -- this can invoke arbitrary
484 * __repr__ overrides, so requires a mostly-intact interpreter.
485 * Alas, a lot of stuff may still be alive now that will be cleaned
486 * up later.
487 */
488 if (Py_GETENV("PYTHONDUMPREFS"))
489 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000490#endif /* Py_TRACE_REFS */
491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 /* Clear interpreter state */
493 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* Now we decref the exception classes. After this point nothing
496 can raise an exception. That's okay, because each Fini() method
497 below has been checked to make sure no exceptions are ever
498 raised.
499 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000504#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000506#endif /* WITH_THREAD */
507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 /* Delete current thread */
509 PyThreadState_Swap(NULL);
510 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 /* Sundry finalizers */
513 PyMethod_Fini();
514 PyFrame_Fini();
515 PyCFunction_Fini();
516 PyTuple_Fini();
517 PyList_Fini();
518 PySet_Fini();
519 PyBytes_Fini();
520 PyByteArray_Fini();
521 PyLong_Fini();
522 PyFloat_Fini();
523 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Cleanup Unicode implementation */
526 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000529 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 free((char*)Py_FileSystemDefaultEncoding);
531 Py_FileSystemDefaultEncoding = NULL;
532 }
Christian Heimesc8967002007-11-30 10:18:26 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 /* XXX Still allocated:
535 - various static ad-hoc pointers to interned strings
536 - int and float free list blocks
537 - whatever various modules and libraries allocate
538 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000541
Tim Peters269b2a62003-04-17 19:52:29 +0000542#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 /* Display addresses (& refcnts) of all objects still alive.
544 * An address can be used to find the repr of the object, printed
545 * above by _Py_PrintReferences.
546 */
547 if (Py_GETENV("PYTHONDUMPREFS"))
548 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000549#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000550#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (Py_GETENV("PYTHONMALLOCSTATS"))
552 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000553#endif
554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556}
557
558/* Create and initialize a new interpreter and thread, and return the
559 new thread. This requires that Py_Initialize() has been called
560 first.
561
562 Unsuccessful initialization yields a NULL pointer. Note that *no*
563 exception information is available even in this case -- the
564 exception information is held in the thread, and there is no
565 thread.
566
567 Locking: as above.
568
569*/
570
571PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000572Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 PyInterpreterState *interp;
575 PyThreadState *tstate, *save_tstate;
576 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (!initialized)
579 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 interp = PyInterpreterState_New();
582 if (interp == NULL)
583 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 tstate = PyThreadState_New(interp);
586 if (tstate == NULL) {
587 PyInterpreterState_Delete(interp);
588 return NULL;
589 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 interp->modules = PyDict_New();
596 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000597
Victor Stinner49d3f252010-10-17 01:24:53 +0000598 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (bimod != NULL) {
600 interp->builtins = PyModule_GetDict(bimod);
601 if (interp->builtins == NULL)
602 goto handle_error;
603 Py_INCREF(interp->builtins);
604 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 /* initialize builtin exceptions */
607 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000608
Victor Stinner49d3f252010-10-17 01:24:53 +0000609 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (bimod != NULL && sysmod != NULL) {
611 PyObject *pstderr;
612 interp->sysdict = PyModule_GetDict(sysmod);
613 if (interp->sysdict == NULL)
614 goto handle_error;
615 Py_INCREF(interp->sysdict);
616 PySys_SetPath(Py_GetPath());
617 PyDict_SetItemString(interp->sysdict, "modules",
618 interp->modules);
619 /* Set up a preliminary stderr printer until we have enough
620 infrastructure for the io module in place. */
621 pstderr = PyFile_NewStdPrinter(fileno(stderr));
622 if (pstderr == NULL)
623 Py_FatalError("Py_Initialize: can't set preliminary stderr");
624 PySys_SetObject("stderr", pstderr);
625 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000626 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200629
630 if (initfsencoding(interp) < 0)
631 goto handle_error;
632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if (initstdio() < 0)
634 Py_FatalError(
635 "Py_Initialize: can't initialize sys standard streams");
636 initmain();
637 if (!Py_NoSiteFlag)
638 initsite();
639 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (!PyErr_Occurred())
642 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000643
Thomas Wouters89f507f2006-12-13 04:49:30 +0000644handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000646
Victor Stinnerc40a3502011-04-27 00:20:27 +0200647 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyThreadState_Clear(tstate);
649 PyThreadState_Swap(save_tstate);
650 PyThreadState_Delete(tstate);
651 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000654}
655
656/* Delete an interpreter and its last thread. This requires that the
657 given thread state is current, that the thread has no remaining
658 frames, and that it is its interpreter's only remaining thread.
659 It is a fatal error to violate these constraints.
660
661 (Py_Finalize() doesn't have these constraints -- it zaps
662 everything, regardless.)
663
664 Locking: as above.
665
666*/
667
668void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000669Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 if (tstate != PyThreadState_GET())
674 Py_FatalError("Py_EndInterpreter: thread is not current");
675 if (tstate->frame != NULL)
676 Py_FatalError("Py_EndInterpreter: thread still has a frame");
677 if (tstate != interp->tstate_head || tstate->next != NULL)
678 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 PyImport_Cleanup();
681 PyInterpreterState_Clear(interp);
682 PyThreadState_Swap(NULL);
683 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000684}
685
Martin v. Löwis790465f2008-04-05 20:41:37 +0000686static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000687
688void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000689Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (pn && *pn)
692 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000693}
694
Martin v. Löwis790465f2008-04-05 20:41:37 +0000695wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000696Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000699}
700
Martin v. Löwis790465f2008-04-05 20:41:37 +0000701static wchar_t *default_home = NULL;
702static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000703
704void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000705Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000708}
709
Martin v. Löwis790465f2008-04-05 20:41:37 +0000710wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000711Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 wchar_t *home = default_home;
714 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
715 char* chome = Py_GETENV("PYTHONHOME");
716 if (chome) {
717 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
718 if (r != (size_t)-1 && r <= PATH_MAX)
719 home = env_home;
720 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 }
723 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000724}
725
Guido van Rossum6135a871995-01-09 17:53:26 +0000726/* Create __main__ module */
727
728static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000729initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 PyObject *m, *d;
732 m = PyImport_AddModule("__main__");
733 if (m == NULL)
734 Py_FatalError("can't create __main__ module");
735 d = PyModule_GetDict(m);
736 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
737 PyObject *bimod = PyImport_ImportModule("builtins");
738 if (bimod == NULL ||
739 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
740 Py_FatalError("can't add __builtins__ to __main__");
741 Py_DECREF(bimod);
742 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000743}
744
Victor Stinner793b5312011-04-27 00:24:21 +0200745static int
746initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000747{
748 PyObject *codec;
749#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000750 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000751
Victor Stinner7f84ab52010-06-11 00:36:33 +0000752 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000753 /* On Unix, set the file system encoding according to the
754 user's preference, if the CODESET names a well-known
755 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000756 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000757 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000758 if (codeset == NULL)
759 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000760
Victor Stinnere4743092010-10-19 00:05:51 +0000761 Py_FileSystemDefaultEncoding = codeset;
762 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200763 interp->fscodec_initialized = 1;
764 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000765 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000766#endif
767
768 /* the encoding is mbcs, utf-8 or ascii */
769 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
770 if (!codec) {
771 /* Such error can only occurs in critical situations: no more
772 * memory, import a module of the standard library failed,
773 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200774 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000775 }
Victor Stinner793b5312011-04-27 00:24:21 +0200776 Py_DECREF(codec);
777 interp->fscodec_initialized = 1;
778 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000779}
780
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000781/* Import the site module (not into __main__ though) */
782
783static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000784initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 PyObject *m;
787 m = PyImport_ImportModule("site");
788 if (m == NULL) {
789 PyErr_Print();
790 Py_Finalize();
791 exit(1);
792 }
793 else {
794 Py_DECREF(m);
795 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000796}
797
Antoine Pitrou05608432009-01-09 18:53:14 +0000798static PyObject*
799create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 int fd, int write_mode, char* name,
801 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
804 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000805 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 PyObject *line_buffering;
807 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 /* stdin is always opened in buffered mode, first because it shouldn't
810 make a difference in common use cases, second because TextIOWrapper
811 depends on the presence of a read1() method which only exists on
812 buffered streams.
813 */
814 if (Py_UnbufferedStdioFlag && write_mode)
815 buffering = 0;
816 else
817 buffering = -1;
818 if (write_mode)
819 mode = "wb";
820 else
821 mode = "rb";
822 buf = PyObject_CallMethod(io, "open", "isiOOOi",
823 fd, mode, buffering,
824 Py_None, Py_None, Py_None, 0);
825 if (buf == NULL)
826 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (buffering) {
829 raw = PyObject_GetAttrString(buf, "raw");
830 if (raw == NULL)
831 goto error;
832 }
833 else {
834 raw = buf;
835 Py_INCREF(raw);
836 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 text = PyUnicode_FromString(name);
839 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
840 goto error;
841 res = PyObject_CallMethod(raw, "isatty", "");
842 if (res == NULL)
843 goto error;
844 isatty = PyObject_IsTrue(res);
845 Py_DECREF(res);
846 if (isatty == -1)
847 goto error;
848 if (isatty || Py_UnbufferedStdioFlag)
849 line_buffering = Py_True;
850 else
851 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 Py_CLEAR(raw);
854 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000855
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000856 newline = "\n";
857#ifdef MS_WINDOWS
858 if (!write_mode) {
859 /* translate \r\n to \n for sys.stdin on Windows */
860 newline = NULL;
861 }
862#endif
863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
865 buf, encoding, errors,
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000866 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 Py_CLEAR(buf);
868 if (stream == NULL)
869 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 if (write_mode)
872 mode = "w";
873 else
874 mode = "r";
875 text = PyUnicode_FromString(mode);
876 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
877 goto error;
878 Py_CLEAR(text);
879 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000880
881error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 Py_XDECREF(buf);
883 Py_XDECREF(stream);
884 Py_XDECREF(text);
885 Py_XDECREF(raw);
886 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000887}
888
Georg Brandl1a3284e2007-12-02 09:40:06 +0000889/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000890static int
891initstdio(void)
892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 PyObject *iomod = NULL, *wrapper;
894 PyObject *bimod = NULL;
895 PyObject *m;
896 PyObject *std = NULL;
897 int status = 0, fd;
898 PyObject * encoding_attr;
899 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 /* Hack to avoid a nasty recursion issue when Python is invoked
902 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
903 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
904 goto error;
905 }
906 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
909 goto error;
910 }
911 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 if (!(bimod = PyImport_ImportModule("builtins"))) {
914 goto error;
915 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 if (!(iomod = PyImport_ImportModule("io"))) {
918 goto error;
919 }
920 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
921 goto error;
922 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Set builtins.open */
925 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000926 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 goto error;
928 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000929 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 encoding = Py_GETENV("PYTHONIOENCODING");
932 errors = NULL;
933 if (encoding) {
934 encoding = strdup(encoding);
935 errors = strchr(encoding, ':');
936 if (errors) {
937 *errors = '\0';
938 errors++;
939 }
940 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Set sys.stdin */
943 fd = fileno(stdin);
944 /* Under some conditions stdin, stdout and stderr may not be connected
945 * and fileno() may point to an invalid file descriptor. For example
946 * GUI apps don't have valid standard streams by default.
947 */
948 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000949#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 std = Py_None;
951 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000952#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000954#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 }
956 else {
957 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
958 if (std == NULL)
959 goto error;
960 } /* if (fd < 0) */
961 PySys_SetObject("__stdin__", std);
962 PySys_SetObject("stdin", std);
963 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 /* Set sys.stdout */
966 fd = fileno(stdout);
967 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000968#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 std = Py_None;
970 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000971#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000973#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 }
975 else {
976 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
977 if (std == NULL)
978 goto error;
979 } /* if (fd < 0) */
980 PySys_SetObject("__stdout__", std);
981 PySys_SetObject("stdout", std);
982 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000983
Guido van Rossum98297ee2007-11-06 21:34:58 +0000984#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 /* Set sys.stderr, replaces the preliminary stderr */
986 fd = fileno(stderr);
987 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000988#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 std = Py_None;
990 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000991#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000993#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 }
995 else {
996 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
997 if (std == NULL)
998 goto error;
999 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 /* Same as hack above, pre-import stderr's codec to avoid recursion
1002 when import.c tries to write to stderr in verbose mode. */
1003 encoding_attr = PyObject_GetAttrString(std, "encoding");
1004 if (encoding_attr != NULL) {
1005 const char * encoding;
1006 encoding = _PyUnicode_AsString(encoding_attr);
1007 if (encoding != NULL) {
1008 _PyCodec_Lookup(encoding);
1009 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001010 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 }
1012 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 PySys_SetObject("__stderr__", std);
1015 PySys_SetObject("stderr", std);
1016 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001017#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001020 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 status = -1;
1022 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 if (encoding)
1025 free(encoding);
1026 Py_XDECREF(bimod);
1027 Py_XDECREF(iomod);
1028 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001029}
1030
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001031/* Parse input from a file and execute it */
1032
1033int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001034PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 if (filename == NULL)
1038 filename = "???";
1039 if (Py_FdIsInteractive(fp, filename)) {
1040 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1041 if (closeit)
1042 fclose(fp);
1043 return err;
1044 }
1045 else
1046 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001047}
1048
1049int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001050PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 PyObject *v;
1053 int ret;
1054 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (flags == NULL) {
1057 flags = &local_flags;
1058 local_flags.cf_flags = 0;
1059 }
1060 v = PySys_GetObject("ps1");
1061 if (v == NULL) {
1062 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1063 Py_XDECREF(v);
1064 }
1065 v = PySys_GetObject("ps2");
1066 if (v == NULL) {
1067 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1068 Py_XDECREF(v);
1069 }
1070 for (;;) {
1071 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1072 PRINT_TOTAL_REFS();
1073 if (ret == E_EOF)
1074 return 0;
1075 /*
1076 if (ret == E_NOMEM)
1077 return -1;
1078 */
1079 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001080}
1081
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001082/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001083static int PARSER_FLAGS(PyCompilerFlags *flags)
1084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 int parser_flags = 0;
1086 if (!flags)
1087 return 0;
1088 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1089 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1090 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1091 parser_flags |= PyPARSE_IGNORE_COOKIE;
1092 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1093 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1094 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001095}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001096
Thomas Wouters89f507f2006-12-13 04:49:30 +00001097#if 0
1098/* Keep an example of flags with future keyword support. */
1099#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1101 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1102 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1103 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001104#endif
1105
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001106int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001107PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyObject *m, *d, *v, *w, *oenc = NULL;
1110 mod_ty mod;
1111 PyArena *arena;
1112 char *ps1 = "", *ps2 = "", *enc = NULL;
1113 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (fp == stdin) {
1116 /* Fetch encoding from sys.stdin */
1117 v = PySys_GetObject("stdin");
1118 if (v == NULL || v == Py_None)
1119 return -1;
1120 oenc = PyObject_GetAttrString(v, "encoding");
1121 if (!oenc)
1122 return -1;
1123 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001124 if (enc == NULL)
1125 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 }
1127 v = PySys_GetObject("ps1");
1128 if (v != NULL) {
1129 v = PyObject_Str(v);
1130 if (v == NULL)
1131 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001132 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001134 if (ps1 == NULL) {
1135 PyErr_Clear();
1136 ps1 = "";
1137 }
1138 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 }
1140 w = PySys_GetObject("ps2");
1141 if (w != NULL) {
1142 w = PyObject_Str(w);
1143 if (w == NULL)
1144 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001145 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001147 if (ps2 == NULL) {
1148 PyErr_Clear();
1149 ps2 = "";
1150 }
1151 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 }
1153 arena = PyArena_New();
1154 if (arena == NULL) {
1155 Py_XDECREF(v);
1156 Py_XDECREF(w);
1157 Py_XDECREF(oenc);
1158 return -1;
1159 }
1160 mod = PyParser_ASTFromFile(fp, filename, enc,
1161 Py_single_input, ps1, ps2,
1162 flags, &errcode, arena);
1163 Py_XDECREF(v);
1164 Py_XDECREF(w);
1165 Py_XDECREF(oenc);
1166 if (mod == NULL) {
1167 PyArena_Free(arena);
1168 if (errcode == E_EOF) {
1169 PyErr_Clear();
1170 return E_EOF;
1171 }
1172 PyErr_Print();
1173 return -1;
1174 }
1175 m = PyImport_AddModule("__main__");
1176 if (m == NULL) {
1177 PyArena_Free(arena);
1178 return -1;
1179 }
1180 d = PyModule_GetDict(m);
1181 v = run_mod(mod, filename, d, d, flags, arena);
1182 PyArena_Free(arena);
1183 flush_io();
1184 if (v == NULL) {
1185 PyErr_Print();
1186 return -1;
1187 }
1188 Py_DECREF(v);
1189 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001190}
1191
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001192/* Check whether a file maybe a pyc file: Look at the extension,
1193 the file type, and, if we may close it, at the first few bytes. */
1194
1195static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001196maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1199 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 /* Only look into the file if we are allowed to close it, since
1202 it then should also be seekable. */
1203 if (closeit) {
1204 /* Read only two bytes of the magic. If the file was opened in
1205 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1206 be read as they are on disk. */
1207 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1208 unsigned char buf[2];
1209 /* Mess: In case of -x, the stream is NOT at its start now,
1210 and ungetc() was used to push back the first newline,
1211 which makes the current stream position formally undefined,
1212 and a x-platform nightmare.
1213 Unfortunately, we have no direct way to know whether -x
1214 was specified. So we use a terrible hack: if the current
1215 stream position is not 0, we assume -x was specified, and
1216 give up. Bug 132850 on SourceForge spells out the
1217 hopelessness of trying anything else (fseek and ftell
1218 don't work predictably x-platform for text-mode files).
1219 */
1220 int ispyc = 0;
1221 if (ftell(fp) == 0) {
1222 if (fread(buf, 1, 2, fp) == 2 &&
1223 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1224 ispyc = 1;
1225 rewind(fp);
1226 }
1227 return ispyc;
1228 }
1229 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001230}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001231
Guido van Rossum0df002c2000-08-27 19:21:52 +00001232int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001233PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 PyObject *m, *d, *v;
1237 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001238 int set_file_name = 0, ret;
1239 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 m = PyImport_AddModule("__main__");
1242 if (m == NULL)
1243 return -1;
1244 d = PyModule_GetDict(m);
1245 if (PyDict_GetItemString(d, "__file__") == NULL) {
1246 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001247 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (f == NULL)
1249 return -1;
1250 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1251 Py_DECREF(f);
1252 return -1;
1253 }
1254 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1255 return -1;
1256 set_file_name = 1;
1257 Py_DECREF(f);
1258 }
1259 len = strlen(filename);
1260 ext = filename + len - (len > 4 ? 4 : 0);
1261 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1262 /* Try to run a pyc file. First, re-open in binary */
1263 if (closeit)
1264 fclose(fp);
1265 if ((fp = fopen(filename, "rb")) == NULL) {
1266 fprintf(stderr, "python: Can't reopen .pyc file\n");
1267 ret = -1;
1268 goto done;
1269 }
1270 /* Turn on optimization if a .pyo file is given */
1271 if (strcmp(ext, ".pyo") == 0)
1272 Py_OptimizeFlag = 1;
1273 v = run_pyc_file(fp, filename, d, d, flags);
1274 } else {
1275 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1276 closeit, flags);
1277 }
1278 flush_io();
1279 if (v == NULL) {
1280 PyErr_Print();
1281 ret = -1;
1282 goto done;
1283 }
1284 Py_DECREF(v);
1285 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001286 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1288 PyErr_Clear();
1289 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001290}
1291
1292int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001293PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 PyObject *m, *d, *v;
1296 m = PyImport_AddModule("__main__");
1297 if (m == NULL)
1298 return -1;
1299 d = PyModule_GetDict(m);
1300 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1301 if (v == NULL) {
1302 PyErr_Print();
1303 return -1;
1304 }
1305 Py_DECREF(v);
1306 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001307}
1308
Barry Warsaw035574d1997-08-29 22:07:17 +00001309static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001310parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 long hold;
1314 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 /* old style errors */
1317 if (PyTuple_Check(err))
1318 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1319 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (! (v = PyObject_GetAttrString(err, "msg")))
1324 goto finally;
1325 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (!(v = PyObject_GetAttrString(err, "filename")))
1328 goto finally;
1329 if (v == Py_None)
1330 *filename = NULL;
1331 else if (! (*filename = _PyUnicode_AsString(v)))
1332 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 Py_DECREF(v);
1335 if (!(v = PyObject_GetAttrString(err, "lineno")))
1336 goto finally;
1337 hold = PyLong_AsLong(v);
1338 Py_DECREF(v);
1339 v = NULL;
1340 if (hold < 0 && PyErr_Occurred())
1341 goto finally;
1342 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 if (!(v = PyObject_GetAttrString(err, "offset")))
1345 goto finally;
1346 if (v == Py_None) {
1347 *offset = -1;
1348 Py_DECREF(v);
1349 v = NULL;
1350 } else {
1351 hold = PyLong_AsLong(v);
1352 Py_DECREF(v);
1353 v = NULL;
1354 if (hold < 0 && PyErr_Occurred())
1355 goto finally;
1356 *offset = (int)hold;
1357 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 if (!(v = PyObject_GetAttrString(err, "text")))
1360 goto finally;
1361 if (v == Py_None)
1362 *text = NULL;
1363 else if (!PyUnicode_Check(v) ||
1364 !(*text = _PyUnicode_AsString(v)))
1365 goto finally;
1366 Py_DECREF(v);
1367 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001368
1369finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 Py_XDECREF(v);
1371 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001372}
1373
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001374void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001375PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001378}
1379
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001380static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001381print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 char *nl;
1384 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001385 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1386 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 for (;;) {
1388 nl = strchr(text, '\n');
1389 if (nl == NULL || nl-text >= offset)
1390 break;
1391 offset -= (int)(nl+1-text);
1392 text = nl+1;
1393 }
1394 while (*text == ' ' || *text == '\t') {
1395 text++;
1396 offset--;
1397 }
1398 }
1399 PyFile_WriteString(" ", f);
1400 PyFile_WriteString(text, f);
1401 if (*text == '\0' || text[strlen(text)-1] != '\n')
1402 PyFile_WriteString("\n", f);
1403 if (offset == -1)
1404 return;
1405 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001406 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001409}
1410
Guido van Rossum66e8e862001-03-23 17:54:43 +00001411static void
1412handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 PyObject *exception, *value, *tb;
1415 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (Py_InspectFlag)
1418 /* Don't exit if -i flag was given. This flag is set to 0
1419 * when entering interactive mode for inspecting. */
1420 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 PyErr_Fetch(&exception, &value, &tb);
1423 fflush(stdout);
1424 if (value == NULL || value == Py_None)
1425 goto done;
1426 if (PyExceptionInstance_Check(value)) {
1427 /* The error code should be in the `code' attribute. */
1428 PyObject *code = PyObject_GetAttrString(value, "code");
1429 if (code) {
1430 Py_DECREF(value);
1431 value = code;
1432 if (value == Py_None)
1433 goto done;
1434 }
1435 /* If we failed to dig out the 'code' attribute,
1436 just let the else clause below print the error. */
1437 }
1438 if (PyLong_Check(value))
1439 exitcode = (int)PyLong_AsLong(value);
1440 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001441 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001442 if (sys_stderr != NULL && sys_stderr != Py_None) {
1443 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1444 } else {
1445 PyObject_Print(value, stderr, Py_PRINT_RAW);
1446 fflush(stderr);
1447 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 PySys_WriteStderr("\n");
1449 exitcode = 1;
1450 }
Tim Peterscf615b52003-04-19 18:47:02 +00001451 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 /* Restore and clear the exception info, in order to properly decref
1453 * the exception, value, and traceback. If we just exit instead,
1454 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1455 * some finalizers from running.
1456 */
1457 PyErr_Restore(exception, value, tb);
1458 PyErr_Clear();
1459 Py_Exit(exitcode);
1460 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001461}
1462
1463void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001464PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1469 handle_system_exit();
1470 }
1471 PyErr_Fetch(&exception, &v, &tb);
1472 if (exception == NULL)
1473 return;
1474 PyErr_NormalizeException(&exception, &v, &tb);
1475 if (tb == NULL) {
1476 tb = Py_None;
1477 Py_INCREF(tb);
1478 }
1479 PyException_SetTraceback(v, tb);
1480 if (exception == NULL)
1481 return;
1482 /* Now we know v != NULL too */
1483 if (set_sys_last_vars) {
1484 PySys_SetObject("last_type", exception);
1485 PySys_SetObject("last_value", v);
1486 PySys_SetObject("last_traceback", tb);
1487 }
1488 hook = PySys_GetObject("excepthook");
1489 if (hook) {
1490 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1491 PyObject *result = PyEval_CallObject(hook, args);
1492 if (result == NULL) {
1493 PyObject *exception2, *v2, *tb2;
1494 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1495 handle_system_exit();
1496 }
1497 PyErr_Fetch(&exception2, &v2, &tb2);
1498 PyErr_NormalizeException(&exception2, &v2, &tb2);
1499 /* It should not be possible for exception2 or v2
1500 to be NULL. However PyErr_Display() can't
1501 tolerate NULLs, so just be safe. */
1502 if (exception2 == NULL) {
1503 exception2 = Py_None;
1504 Py_INCREF(exception2);
1505 }
1506 if (v2 == NULL) {
1507 v2 = Py_None;
1508 Py_INCREF(v2);
1509 }
1510 fflush(stdout);
1511 PySys_WriteStderr("Error in sys.excepthook:\n");
1512 PyErr_Display(exception2, v2, tb2);
1513 PySys_WriteStderr("\nOriginal exception was:\n");
1514 PyErr_Display(exception, v, tb);
1515 Py_DECREF(exception2);
1516 Py_DECREF(v2);
1517 Py_XDECREF(tb2);
1518 }
1519 Py_XDECREF(result);
1520 Py_XDECREF(args);
1521 } else {
1522 PySys_WriteStderr("sys.excepthook is missing\n");
1523 PyErr_Display(exception, v, tb);
1524 }
1525 Py_XDECREF(exception);
1526 Py_XDECREF(v);
1527 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001528}
1529
Benjamin Petersone6528212008-07-15 15:32:09 +00001530static void
1531print_exception(PyObject *f, PyObject *value)
1532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 int err = 0;
1534 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 if (!PyExceptionInstance_Check(value)) {
1537 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1538 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1539 PyFile_WriteString(" found\n", f);
1540 return;
1541 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 Py_INCREF(value);
1544 fflush(stdout);
1545 type = (PyObject *) Py_TYPE(value);
1546 tb = PyException_GetTraceback(value);
1547 if (tb && tb != Py_None)
1548 err = PyTraceBack_Print(tb, f);
1549 if (err == 0 &&
1550 PyObject_HasAttrString(value, "print_file_and_line"))
1551 {
1552 PyObject *message;
1553 const char *filename, *text;
1554 int lineno, offset;
1555 if (!parse_syntax_error(value, &message, &filename,
1556 &lineno, &offset, &text))
1557 PyErr_Clear();
1558 else {
1559 char buf[10];
1560 PyFile_WriteString(" File \"", f);
1561 if (filename == NULL)
1562 PyFile_WriteString("<string>", f);
1563 else
1564 PyFile_WriteString(filename, f);
1565 PyFile_WriteString("\", line ", f);
1566 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1567 PyFile_WriteString(buf, f);
1568 PyFile_WriteString("\n", f);
1569 if (text != NULL)
1570 print_error_text(f, offset, text);
1571 Py_DECREF(value);
1572 value = message;
1573 /* Can't be bothered to check all those
1574 PyFile_WriteString() calls */
1575 if (PyErr_Occurred())
1576 err = -1;
1577 }
1578 }
1579 if (err) {
1580 /* Don't do anything else */
1581 }
1582 else {
1583 PyObject* moduleName;
1584 char* className;
1585 assert(PyExceptionClass_Check(type));
1586 className = PyExceptionClass_Name(type);
1587 if (className != NULL) {
1588 char *dot = strrchr(className, '.');
1589 if (dot != NULL)
1590 className = dot+1;
1591 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 moduleName = PyObject_GetAttrString(type, "__module__");
1594 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1595 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001596 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 err = PyFile_WriteString("<unknown>", f);
1598 }
1599 else {
1600 char* modstr = _PyUnicode_AsString(moduleName);
1601 if (modstr && strcmp(modstr, "builtins"))
1602 {
1603 err = PyFile_WriteString(modstr, f);
1604 err += PyFile_WriteString(".", f);
1605 }
1606 Py_DECREF(moduleName);
1607 }
1608 if (err == 0) {
1609 if (className == NULL)
1610 err = PyFile_WriteString("<unknown>", f);
1611 else
1612 err = PyFile_WriteString(className, f);
1613 }
1614 }
1615 if (err == 0 && (value != Py_None)) {
1616 PyObject *s = PyObject_Str(value);
1617 /* only print colon if the str() of the
1618 object is not the empty string
1619 */
1620 if (s == NULL)
1621 err = -1;
1622 else if (!PyUnicode_Check(s) ||
1623 PyUnicode_GetSize(s) != 0)
1624 err = PyFile_WriteString(": ", f);
1625 if (err == 0)
1626 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1627 Py_XDECREF(s);
1628 }
1629 /* try to write a newline in any case */
1630 err += PyFile_WriteString("\n", f);
1631 Py_XDECREF(tb);
1632 Py_DECREF(value);
1633 /* If an error happened here, don't show it.
1634 XXX This is wrong, but too many callers rely on this behavior. */
1635 if (err != 0)
1636 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001637}
1638
1639static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 "\nThe above exception was the direct cause "
1641 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001642
1643static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 "\nDuring handling of the above exception, "
1645 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001646
1647static void
1648print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 int err = 0, res;
1651 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 if (seen != NULL) {
1654 /* Exception chaining */
1655 if (PySet_Add(seen, value) == -1)
1656 PyErr_Clear();
1657 else if (PyExceptionInstance_Check(value)) {
1658 cause = PyException_GetCause(value);
1659 context = PyException_GetContext(value);
1660 if (cause) {
1661 res = PySet_Contains(seen, cause);
1662 if (res == -1)
1663 PyErr_Clear();
1664 if (res == 0) {
1665 print_exception_recursive(
1666 f, cause, seen);
1667 err |= PyFile_WriteString(
1668 cause_message, f);
1669 }
1670 }
1671 else if (context) {
1672 res = PySet_Contains(seen, context);
1673 if (res == -1)
1674 PyErr_Clear();
1675 if (res == 0) {
1676 print_exception_recursive(
1677 f, context, seen);
1678 err |= PyFile_WriteString(
1679 context_message, f);
1680 }
1681 }
1682 Py_XDECREF(context);
1683 Py_XDECREF(cause);
1684 }
1685 }
1686 print_exception(f, value);
1687 if (err != 0)
1688 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001689}
1690
Thomas Wouters477c8d52006-05-27 19:21:47 +00001691void
1692PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyObject *seen;
1695 PyObject *f = PySys_GetObject("stderr");
1696 if (f == Py_None) {
1697 /* pass */
1698 }
1699 else if (f == NULL) {
1700 _PyObject_Dump(value);
1701 fprintf(stderr, "lost sys.stderr\n");
1702 }
1703 else {
1704 /* We choose to ignore seen being possibly NULL, and report
1705 at least the main exception (it could be a MemoryError).
1706 */
1707 seen = PySet_New(NULL);
1708 if (seen == NULL)
1709 PyErr_Clear();
1710 print_exception_recursive(f, value, seen);
1711 Py_XDECREF(seen);
1712 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001713}
1714
Guido van Rossum82598051997-03-05 00:20:32 +00001715PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001716PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyObject *ret = NULL;
1720 mod_ty mod;
1721 PyArena *arena = PyArena_New();
1722 if (arena == NULL)
1723 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1726 if (mod != NULL)
1727 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1728 PyArena_Free(arena);
1729 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001730}
1731
1732PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001733PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyObject *ret;
1737 mod_ty mod;
1738 PyArena *arena = PyArena_New();
1739 if (arena == NULL)
1740 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1743 flags, NULL, arena);
1744 if (closeit)
1745 fclose(fp);
1746 if (mod == NULL) {
1747 PyArena_Free(arena);
1748 return NULL;
1749 }
1750 ret = run_mod(mod, filename, globals, locals, flags, arena);
1751 PyArena_Free(arena);
1752 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001753}
1754
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001755static void
1756flush_io(void)
1757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 PyObject *f, *r;
1759 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 /* Save the current exception */
1762 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 f = PySys_GetObject("stderr");
1765 if (f != NULL) {
1766 r = PyObject_CallMethod(f, "flush", "");
1767 if (r)
1768 Py_DECREF(r);
1769 else
1770 PyErr_Clear();
1771 }
1772 f = PySys_GetObject("stdout");
1773 if (f != NULL) {
1774 r = PyObject_CallMethod(f, "flush", "");
1775 if (r)
1776 Py_DECREF(r);
1777 else
1778 PyErr_Clear();
1779 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001782}
1783
Guido van Rossum82598051997-03-05 00:20:32 +00001784static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 PyCodeObject *co;
1789 PyObject *v;
1790 co = PyAST_Compile(mod, filename, flags, arena);
1791 if (co == NULL)
1792 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001793 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 Py_DECREF(co);
1795 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001796}
1797
Guido van Rossum82598051997-03-05 00:20:32 +00001798static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001799run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 PyCodeObject *co;
1803 PyObject *v;
1804 long magic;
1805 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 magic = PyMarshal_ReadLongFromFile(fp);
1808 if (magic != PyImport_GetMagicNumber()) {
1809 PyErr_SetString(PyExc_RuntimeError,
1810 "Bad magic number in .pyc file");
1811 return NULL;
1812 }
1813 (void) PyMarshal_ReadLongFromFile(fp);
1814 v = PyMarshal_ReadLastObjectFromFile(fp);
1815 fclose(fp);
1816 if (v == NULL || !PyCode_Check(v)) {
1817 Py_XDECREF(v);
1818 PyErr_SetString(PyExc_RuntimeError,
1819 "Bad code object in .pyc file");
1820 return NULL;
1821 }
1822 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001823 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 if (v && flags)
1825 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1826 Py_DECREF(co);
1827 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001828}
1829
Guido van Rossum82598051997-03-05 00:20:32 +00001830PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001831Py_CompileStringExFlags(const char *str, const char *filename, int start,
1832 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 PyCodeObject *co;
1835 mod_ty mod;
1836 PyArena *arena = PyArena_New();
1837 if (arena == NULL)
1838 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1841 if (mod == NULL) {
1842 PyArena_Free(arena);
1843 return NULL;
1844 }
1845 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1846 PyObject *result = PyAST_mod2obj(mod);
1847 PyArena_Free(arena);
1848 return result;
1849 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001850 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 PyArena_Free(arena);
1852 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001853}
1854
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001855/* For use in Py_LIMITED_API */
1856#undef Py_CompileString
1857PyObject *
1858PyCompileString(const char *str, const char *filename, int start)
1859{
1860 return Py_CompileStringFlags(str, filename, start, NULL);
1861}
1862
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001863struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001864Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 struct symtable *st;
1867 mod_ty mod;
1868 PyCompilerFlags flags;
1869 PyArena *arena = PyArena_New();
1870 if (arena == NULL)
1871 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 flags.cf_flags = 0;
1874 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1875 if (mod == NULL) {
1876 PyArena_Free(arena);
1877 return NULL;
1878 }
1879 st = PySymtable_Build(mod, filename, 0);
1880 PyArena_Free(arena);
1881 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001882}
1883
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884/* Preferred access to parser is through AST. */
1885mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001886PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 mod_ty mod;
1890 PyCompilerFlags localflags;
1891 perrdetail err;
1892 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1895 &_PyParser_Grammar, start, &err,
1896 &iflags);
1897 if (flags == NULL) {
1898 localflags.cf_flags = 0;
1899 flags = &localflags;
1900 }
1901 if (n) {
1902 flags->cf_flags |= iflags & PyCF_MASK;
1903 mod = PyAST_FromNode(n, flags, filename, arena);
1904 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 }
1906 else {
1907 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001908 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001910 err_free(&err);
1911 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912}
1913
1914mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001915PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 int start, char *ps1,
1917 char *ps2, PyCompilerFlags *flags, int *errcode,
1918 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 mod_ty mod;
1921 PyCompilerFlags localflags;
1922 perrdetail err;
1923 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1926 &_PyParser_Grammar,
1927 start, ps1, ps2, &err, &iflags);
1928 if (flags == NULL) {
1929 localflags.cf_flags = 0;
1930 flags = &localflags;
1931 }
1932 if (n) {
1933 flags->cf_flags |= iflags & PyCF_MASK;
1934 mod = PyAST_FromNode(n, flags, filename, arena);
1935 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 }
1937 else {
1938 err_input(&err);
1939 if (errcode)
1940 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02001941 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001943 err_free(&err);
1944 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001945}
1946
Guido van Rossuma110aa61994-08-29 12:50:44 +00001947/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001948
Guido van Rossuma110aa61994-08-29 12:50:44 +00001949node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001950PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 perrdetail err;
1953 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1954 &_PyParser_Grammar,
1955 start, NULL, NULL, &err, flags);
1956 if (n == NULL)
1957 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001958 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001961}
1962
Guido van Rossuma110aa61994-08-29 12:50:44 +00001963/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001964
Guido van Rossuma110aa61994-08-29 12:50:44 +00001965node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001966PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 perrdetail err;
1969 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1970 start, &err, flags);
1971 if (n == NULL)
1972 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001973 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001975}
1976
1977node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001978PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 perrdetail err;
1982 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1983 &_PyParser_Grammar, start, &err, flags);
1984 if (n == NULL)
1985 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001986 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001988}
1989
1990node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001991PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001994}
1995
Guido van Rossum66ebd912003-04-17 16:02:26 +00001996/* May want to move a more generalized form of this to parsetok.c or
1997 even parser modules. */
1998
1999void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002000PyParser_ClearError(perrdetail *err)
2001{
2002 err_free(err);
2003}
2004
2005void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002006PyParser_SetError(perrdetail *err)
2007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002009}
2010
Victor Stinner7f2fee32011-04-05 00:39:01 +02002011static void
2012err_free(perrdetail *err)
2013{
2014 Py_CLEAR(err->filename);
2015}
2016
Guido van Rossuma110aa61994-08-29 12:50:44 +00002017/* Set the error appropriate to the given input error code (see errcode.h) */
2018
2019static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002020err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 PyObject *v, *w, *errtype, *errtext;
2023 PyObject *msg_obj = NULL;
2024 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 errtype = PyExc_SyntaxError;
2027 switch (err->error) {
2028 case E_ERROR:
2029 return;
2030 case E_SYNTAX:
2031 errtype = PyExc_IndentationError;
2032 if (err->expected == INDENT)
2033 msg = "expected an indented block";
2034 else if (err->token == INDENT)
2035 msg = "unexpected indent";
2036 else if (err->token == DEDENT)
2037 msg = "unexpected unindent";
2038 else {
2039 errtype = PyExc_SyntaxError;
2040 msg = "invalid syntax";
2041 }
2042 break;
2043 case E_TOKEN:
2044 msg = "invalid token";
2045 break;
2046 case E_EOFS:
2047 msg = "EOF while scanning triple-quoted string literal";
2048 break;
2049 case E_EOLS:
2050 msg = "EOL while scanning string literal";
2051 break;
2052 case E_INTR:
2053 if (!PyErr_Occurred())
2054 PyErr_SetNone(PyExc_KeyboardInterrupt);
2055 goto cleanup;
2056 case E_NOMEM:
2057 PyErr_NoMemory();
2058 goto cleanup;
2059 case E_EOF:
2060 msg = "unexpected EOF while parsing";
2061 break;
2062 case E_TABSPACE:
2063 errtype = PyExc_TabError;
2064 msg = "inconsistent use of tabs and spaces in indentation";
2065 break;
2066 case E_OVERFLOW:
2067 msg = "expression too long";
2068 break;
2069 case E_DEDENT:
2070 errtype = PyExc_IndentationError;
2071 msg = "unindent does not match any outer indentation level";
2072 break;
2073 case E_TOODEEP:
2074 errtype = PyExc_IndentationError;
2075 msg = "too many levels of indentation";
2076 break;
2077 case E_DECODE: {
2078 PyObject *type, *value, *tb;
2079 PyErr_Fetch(&type, &value, &tb);
2080 msg = "unknown decode error";
2081 if (value != NULL)
2082 msg_obj = PyObject_Str(value);
2083 Py_XDECREF(type);
2084 Py_XDECREF(value);
2085 Py_XDECREF(tb);
2086 break;
2087 }
2088 case E_LINECONT:
2089 msg = "unexpected character after line continuation character";
2090 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 case E_IDENTIFIER:
2093 msg = "invalid character in identifier";
2094 break;
2095 default:
2096 fprintf(stderr, "error=%d\n", err->error);
2097 msg = "unknown parsing error";
2098 break;
2099 }
2100 /* err->text may not be UTF-8 in case of decoding errors.
2101 Explicitly convert to an object. */
2102 if (!err->text) {
2103 errtext = Py_None;
2104 Py_INCREF(Py_None);
2105 } else {
2106 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2107 "replace");
2108 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002109 v = Py_BuildValue("(OiiN)", err->filename,
2110 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 if (v != NULL) {
2112 if (msg_obj)
2113 w = Py_BuildValue("(OO)", msg_obj, v);
2114 else
2115 w = Py_BuildValue("(sO)", msg, v);
2116 } else
2117 w = NULL;
2118 Py_XDECREF(v);
2119 PyErr_SetObject(errtype, w);
2120 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002121cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 Py_XDECREF(msg_obj);
2123 if (err->text != NULL) {
2124 PyObject_FREE(err->text);
2125 err->text = NULL;
2126 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002127}
2128
2129/* Print fatal error message and abort */
2130
2131void
Tim Peters7c321a82002-07-09 02:57:01 +00002132Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002133{
Victor Stinner024e37a2011-03-31 01:31:06 +02002134 const int fd = fileno(stderr);
2135 PyThreadState *tstate;
2136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 fprintf(stderr, "Fatal Python error: %s\n", msg);
2138 fflush(stderr); /* it helps in Windows debug build */
2139 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002140 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002142 else {
2143 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2144 if (tstate != NULL) {
2145 fputc('\n', stderr);
2146 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002147 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002148 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002149 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002150 }
2151
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002152#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 {
2154 size_t len = strlen(msg);
2155 WCHAR* buffer;
2156 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 /* Convert the message to wchar_t. This uses a simple one-to-one
2159 conversion, assuming that the this error message actually uses ASCII
2160 only. If this ceases to be true, we will have to convert. */
2161 buffer = alloca( (len+1) * (sizeof *buffer));
2162 for( i=0; i<=len; ++i)
2163 buffer[i] = msg[i];
2164 OutputDebugStringW(L"Fatal Python error: ");
2165 OutputDebugStringW(buffer);
2166 OutputDebugStringW(L"\n");
2167 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002168#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002170#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002171#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002173}
2174
2175/* Clean up and exit */
2176
Guido van Rossuma110aa61994-08-29 12:50:44 +00002177#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002178#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002179#endif
2180
Collin Winter670e6922007-03-21 02:57:17 +00002181static void (*pyexitfunc)(void) = NULL;
2182/* For the atexit module. */
2183void _Py_PyAtExit(void (*func)(void))
2184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002186}
2187
2188static void
2189call_py_exitfuncs(void)
2190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 if (pyexitfunc == NULL)
2192 return;
Collin Winter670e6922007-03-21 02:57:17 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 (*pyexitfunc)();
2195 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002196}
2197
Antoine Pitrou011bd622009-10-20 21:52:47 +00002198/* Wait until threading._shutdown completes, provided
2199 the threading module was imported in the first place.
2200 The shutdown routine will wait until all non-daemon
2201 "threading" threads have completed. */
2202static void
2203wait_for_thread_shutdown(void)
2204{
2205#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 PyObject *result;
2207 PyThreadState *tstate = PyThreadState_GET();
2208 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2209 "threading");
2210 if (threading == NULL) {
2211 /* threading not imported */
2212 PyErr_Clear();
2213 return;
2214 }
2215 result = PyObject_CallMethod(threading, "_shutdown", "");
2216 if (result == NULL) {
2217 PyErr_WriteUnraisable(threading);
2218 }
2219 else {
2220 Py_DECREF(result);
2221 }
2222 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002223#endif
2224}
2225
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002226#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002227static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002228static int nexitfuncs = 0;
2229
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002230int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if (nexitfuncs >= NEXITFUNCS)
2233 return -1;
2234 exitfuncs[nexitfuncs++] = func;
2235 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002236}
2237
Guido van Rossumcc283f51997-08-05 02:22:03 +00002238static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002239call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 while (nexitfuncs > 0)
2242 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 fflush(stdout);
2245 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002246}
2247
2248void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002249Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002254}
2255
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002256static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002257initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002258{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002259#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002261#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002262#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002264#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002265#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002267#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002269}
2270
Guido van Rossum7433b121997-02-14 19:45:36 +00002271
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002272/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2273 *
2274 * All of the code in this function must only use async-signal-safe functions,
2275 * listed at `man 7 signal` or
2276 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2277 */
2278void
2279_Py_RestoreSignals(void)
2280{
2281#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002283#endif
2284#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002286#endif
2287#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002289#endif
2290}
2291
2292
Guido van Rossum7433b121997-02-14 19:45:36 +00002293/*
2294 * The file descriptor fd is considered ``interactive'' if either
2295 * a) isatty(fd) is TRUE, or
2296 * b) the -i flag was given, and the filename associated with
2297 * the descriptor is NULL or "<stdin>" or "???".
2298 */
2299int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002300Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 if (isatty((int)fileno(fp)))
2303 return 1;
2304 if (!Py_InteractiveFlag)
2305 return 0;
2306 return (filename == NULL) ||
2307 (strcmp(filename, "<stdin>") == 0) ||
2308 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002309}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002310
2311
Tim Petersd08e3822003-04-17 15:24:21 +00002312#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002313#if defined(WIN32) && defined(_MSC_VER)
2314
2315/* Stack checking for Microsoft C */
2316
2317#include <malloc.h>
2318#include <excpt.h>
2319
Fred Drakee8de31c2000-08-31 05:38:39 +00002320/*
2321 * Return non-zero when we run out of memory on the stack; zero otherwise.
2322 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002323int
Fred Drake399739f2000-08-31 05:52:44 +00002324PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 __try {
2327 /* alloca throws a stack overflow exception if there's
2328 not enough space left on the stack */
2329 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2330 return 0;
2331 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2332 EXCEPTION_EXECUTE_HANDLER :
2333 EXCEPTION_CONTINUE_SEARCH) {
2334 int errcode = _resetstkoflw();
2335 if (errcode == 0)
2336 {
2337 Py_FatalError("Could not reset the stack!");
2338 }
2339 }
2340 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002341}
2342
2343#endif /* WIN32 && _MSC_VER */
2344
2345/* Alternate implementations can be added here... */
2346
2347#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002348
2349
2350/* Wrappers around sigaction() or signal(). */
2351
2352PyOS_sighandler_t
2353PyOS_getsig(int sig)
2354{
2355#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 struct sigaction context;
2357 if (sigaction(sig, NULL, &context) == -1)
2358 return SIG_ERR;
2359 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002360#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002362/* Special signal handling for the secure CRT in Visual Studio 2005 */
2363#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 switch (sig) {
2365 /* Only these signals are valid */
2366 case SIGINT:
2367 case SIGILL:
2368 case SIGFPE:
2369 case SIGSEGV:
2370 case SIGTERM:
2371 case SIGBREAK:
2372 case SIGABRT:
2373 break;
2374 /* Don't call signal() with other values or it will assert */
2375 default:
2376 return SIG_ERR;
2377 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002378#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 handler = signal(sig, SIG_IGN);
2380 if (handler != SIG_ERR)
2381 signal(sig, handler);
2382 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002383#endif
2384}
2385
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002386/*
2387 * All of the code in this function must only use async-signal-safe functions,
2388 * listed at `man 7 signal` or
2389 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2390 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002391PyOS_sighandler_t
2392PyOS_setsig(int sig, PyOS_sighandler_t handler)
2393{
2394#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 /* Some code in Modules/signalmodule.c depends on sigaction() being
2396 * used here if HAVE_SIGACTION is defined. Fix that if this code
2397 * changes to invalidate that assumption.
2398 */
2399 struct sigaction context, ocontext;
2400 context.sa_handler = handler;
2401 sigemptyset(&context.sa_mask);
2402 context.sa_flags = 0;
2403 if (sigaction(sig, &context, &ocontext) == -1)
2404 return SIG_ERR;
2405 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002406#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 PyOS_sighandler_t oldhandler;
2408 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002409#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002411#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002413#endif
2414}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002415
2416/* Deprecated C API functions still provided for binary compatiblity */
2417
2418#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002419PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002420PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002423}
2424
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002425#undef PyParser_SimpleParseString
2426PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002427PyParser_SimpleParseString(const char *str, int start)
2428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002430}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002431
2432#undef PyRun_AnyFile
2433PyAPI_FUNC(int)
2434PyRun_AnyFile(FILE *fp, const char *name)
2435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002437}
2438
2439#undef PyRun_AnyFileEx
2440PyAPI_FUNC(int)
2441PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002444}
2445
2446#undef PyRun_AnyFileFlags
2447PyAPI_FUNC(int)
2448PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002451}
2452
2453#undef PyRun_File
2454PyAPI_FUNC(PyObject *)
2455PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002458}
2459
2460#undef PyRun_FileEx
2461PyAPI_FUNC(PyObject *)
2462PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002465}
2466
2467#undef PyRun_FileFlags
2468PyAPI_FUNC(PyObject *)
2469PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002473}
2474
2475#undef PyRun_SimpleFile
2476PyAPI_FUNC(int)
2477PyRun_SimpleFile(FILE *f, const char *p)
2478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002480}
2481
2482#undef PyRun_SimpleFileEx
2483PyAPI_FUNC(int)
2484PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002487}
2488
2489
2490#undef PyRun_String
2491PyAPI_FUNC(PyObject *)
2492PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002495}
2496
2497#undef PyRun_SimpleString
2498PyAPI_FUNC(int)
2499PyRun_SimpleString(const char *s)
2500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002502}
2503
2504#undef Py_CompileString
2505PyAPI_FUNC(PyObject *)
2506Py_CompileString(const char *str, const char *p, int s)
2507{
Georg Brandl8334fd92010-12-04 10:26:46 +00002508 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2509}
2510
2511#undef Py_CompileStringFlags
2512PyAPI_FUNC(PyObject *)
2513Py_CompileStringFlags(const char *str, const char *p, int s,
2514 PyCompilerFlags *flags)
2515{
2516 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002517}
2518
2519#undef PyRun_InteractiveOne
2520PyAPI_FUNC(int)
2521PyRun_InteractiveOne(FILE *f, const char *p)
2522{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002524}
2525
2526#undef PyRun_InteractiveLoop
2527PyAPI_FUNC(int)
2528PyRun_InteractiveLoop(FILE *f, const char *p)
2529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002531}
2532
2533#ifdef __cplusplus
2534}
2535#endif