blob: afb4c510174ba4ebae7ac115f24e6fff5336a398 [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"
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Antoine Pitrouefb60c02009-10-20 21:29:37 +000020#include "abstract.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000021
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000022#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023#include <signal.h>
Martin v. Löwis0e8bd7e2006-06-10 12:23:46 +000024#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000025
Benjamin Peterson796798b2009-01-02 20:47:27 +000026#ifdef MS_WINDOWS
Martin v. Löwis5344c992009-01-02 20:32:55 +000027#include "malloc.h" /* for alloca */
Benjamin Peterson796798b2009-01-02 20:47:27 +000028#endif
Martin v. Löwis5344c992009-01-02 20:32:55 +000029
Martin v. Löwis73d538b2003-03-05 15:13:47 +000030#ifdef HAVE_LANGINFO_H
31#include <locale.h>
32#include <langinfo.h>
33#endif
34
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000035#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#undef BYTE
37#include "windows.h"
38#endif
39
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#ifndef Py_REF_DEBUG
Tim Peters62e97f02006-03-28 21:44:32 +000041#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000042#else /* Py_REF_DEBUG */
Antoine Pitrouc83ea132010-05-09 14:46:46 +000043#define PRINT_TOTAL_REFS() fprintf(stderr, \
44 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
45 _Py_GetRefTotal())
Neal Norwitz4281cef2006-03-04 19:58:13 +000046#endif
47
Anthony Baxterac6bd462006-04-13 02:06:09 +000048#ifdef __cplusplus
49extern "C" {
50#endif
51
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000052extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossum82598051997-03-05 00:20:32 +000054extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000055
Guido van Rossumb73cc041993-11-01 16:28:59 +000056/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initmain(void);
58static void initsite(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000059static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouc83ea132010-05-09 14:46:46 +000060 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000061static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouc83ea132010-05-09 14:46:46 +000062 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000063static void err_input(perrdetail *);
64static void initsigs(void);
Antoine Pitrouefb60c02009-10-20 21:29:37 +000065static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void call_sys_exitfunc(void);
67static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000068extern void _PyUnicode_Init(void);
69extern void _PyUnicode_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000070
Mark Hammond8d98d2c2003-04-19 15:41:53 +000071#ifdef WITH_THREAD
72extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
73extern void _PyGILState_Fini(void);
74#endif /* WITH_THREAD */
75
Guido van Rossum82598051997-03-05 00:20:32 +000076int Py_DebugFlag; /* Needed by parser.c */
77int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000078int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl11041f02011-05-15 08:50:32 +020079int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000080int Py_NoSiteFlag; /* Suppress 'import site' */
Christian Heimes1a6387e2008-03-26 12:49:49 +000081int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Georg Brandl2da0fce2008-01-07 17:09:35 +000082int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000083int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000084int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000085int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000086int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000087/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
88 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
89 true divisions (which they will be in 2.3). */
90int _Py_QnewFlag = 0;
Christian Heimesaf748c32008-05-06 22:41:46 +000091int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Barry Warsaw1e13eb02012-02-20 20:42:21 -050092int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000093
Brett Cannone9746892008-04-12 23:44:07 +000094/* PyModule_GetWarningsModule is no longer necessary as of 2.6
95since _warnings is builtin. This API should not be used. */
96PyObject *
97PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000098{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000099 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000100}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000101
Guido van Rossum25ce5661997-08-02 03:10:38 +0000102static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000103
Thomas Wouters7e474022000-07-16 12:04:32 +0000104/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000105
106int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000107Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000108{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000109 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000110}
111
Guido van Rossum25ce5661997-08-02 03:10:38 +0000112/* Global initializations. Can be undone by Py_Finalize(). Don't
113 call this twice without an intervening Py_Finalize() call. When
114 initializations fail, a fatal error is issued and the function does
115 not return. On return, the first thread and interpreter state have
116 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000117
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118 Locking: you must hold the interpreter lock while calling this.
119 (If the lock has not yet been initialized, that's equivalent to
120 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000121
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000123
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000124static int
125add_flag(int flag, const char *envs)
126{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000127 int env = atoi(envs);
128 if (flag < env)
129 flag = env;
130 if (flag < 1)
131 flag = 1;
132 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000133}
134
Guido van Rossuma027efa1997-05-05 20:56:21 +0000135void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000136Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000137{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000138 PyInterpreterState *interp;
139 PyThreadState *tstate;
140 PyObject *bimod, *sysmod;
141 char *p;
142 char *icodeset = NULL; /* On Windows, input codeset may theoretically
143 differ from output codeset. */
144 char *codeset = NULL;
145 char *errors = NULL;
146 int free_codeset = 0;
147 int overridden = 0;
148 PyObject *sys_stream, *sys_isatty;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000149#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000150 char *saved_locale, *loc_codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000151#endif
Martin v. Löwis99815892008-06-01 07:20:46 +0000152#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000153 char ibuf[128];
154 char buf[128];
Martin v. Löwis99815892008-06-01 07:20:46 +0000155#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000156 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000157
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000158 if (initialized)
159 return;
160 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000161
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000162 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
163 Py_DebugFlag = add_flag(Py_DebugFlag, p);
164 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
165 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
166 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
167 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
168 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
169 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500170 /* The variable is only tested for existence here; _PyRandom_Init will
171 check its value further. */
172 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
173 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
174
175 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000176
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000177 interp = PyInterpreterState_New();
178 if (interp == NULL)
179 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000180
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000181 tstate = PyThreadState_New(interp);
182 if (tstate == NULL)
183 Py_FatalError("Py_Initialize: can't make first thread");
184 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000185
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000186 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000187
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000188 if (!_PyFrame_Init())
189 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000190
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000191 if (!_PyInt_Init())
192 Py_FatalError("Py_Initialize: can't init ints");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000193
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000194 if (!_PyLong_Init())
195 Py_FatalError("Py_Initialize: can't init longs");
Mark Dickinsonefc82f72009-03-20 15:51:55 +0000196
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000197 if (!PyByteArray_Init())
198 Py_FatalError("Py_Initialize: can't init bytearray");
Christian Heimes1a6387e2008-03-26 12:49:49 +0000199
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000200 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000201
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000202 interp->modules = PyDict_New();
203 if (interp->modules == NULL)
204 Py_FatalError("Py_Initialize: can't make modules dictionary");
205 interp->modules_reloading = PyDict_New();
206 if (interp->modules_reloading == NULL)
207 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000208
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000209#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000210 /* Init Unicode implementation; relies on the codec registry */
211 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000212#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000213
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000214 bimod = _PyBuiltin_Init();
215 if (bimod == NULL)
216 Py_FatalError("Py_Initialize: can't initialize __builtin__");
217 interp->builtins = PyModule_GetDict(bimod);
218 if (interp->builtins == NULL)
219 Py_FatalError("Py_Initialize: can't initialize builtins dict");
220 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000221
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000222 sysmod = _PySys_Init();
223 if (sysmod == NULL)
224 Py_FatalError("Py_Initialize: can't initialize sys");
225 interp->sysdict = PyModule_GetDict(sysmod);
226 if (interp->sysdict == NULL)
227 Py_FatalError("Py_Initialize: can't initialize sys dict");
228 Py_INCREF(interp->sysdict);
229 _PyImport_FixupExtension("sys", "sys");
230 PySys_SetPath(Py_GetPath());
231 PyDict_SetItemString(interp->sysdict, "modules",
232 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000233
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000234 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000235
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000236 /* initialize builtin exceptions */
237 _PyExc_Init();
238 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000239
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000240 /* phase 2 of builtins */
241 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000242
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000243 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000244
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000245 if (install_sigs)
246 initsigs(); /* Signal handling stuff, including initintr() */
Brett Cannonc33e82d2010-05-05 20:38:52 +0000247
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000248 /* Initialize warnings. */
249 _PyWarnings_Init();
250 if (PySys_HasWarnOptions()) {
251 PyObject *warnings_module = PyImport_ImportModule("warnings");
252 if (!warnings_module)
253 PyErr_Clear();
254 Py_XDECREF(warnings_module);
255 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000256
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000257 initmain(); /* Module __main__ */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000258
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000259 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000260#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000261 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000262#endif /* WITH_THREAD */
263
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000264 if (!Py_NoSiteFlag)
265 initsite(); /* Module site */
Victor Stinner66644262010-03-10 22:30:19 +0000266
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000267 if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
268 p = icodeset = codeset = strdup(p);
269 free_codeset = 1;
270 errors = strchr(p, ':');
271 if (errors) {
272 *errors = '\0';
273 errors++;
274 }
275 overridden = 1;
276 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000277
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000278#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000279 /* On Unix, set the file system encoding according to the
280 user's preference, if the CODESET names a well-known
281 Python codec, and Py_FileSystemDefaultEncoding isn't
282 initialized by other means. Also set the encoding of
283 stdin and stdout if these are terminals, unless overridden. */
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000284
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000285 if (!overridden || !Py_FileSystemDefaultEncoding) {
286 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
287 setlocale(LC_CTYPE, "");
288 loc_codeset = nl_langinfo(CODESET);
289 if (loc_codeset && *loc_codeset) {
290 PyObject *enc = PyCodec_Encoder(loc_codeset);
291 if (enc) {
292 loc_codeset = strdup(loc_codeset);
293 Py_DECREF(enc);
294 } else {
295 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
296 PyErr_Clear();
297 loc_codeset = NULL;
298 } else {
299 PyErr_Print();
300 exit(1);
301 }
302 }
303 } else
304 loc_codeset = NULL;
305 setlocale(LC_CTYPE, saved_locale);
306 free(saved_locale);
Martin v. Löwis99815892008-06-01 07:20:46 +0000307
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000308 if (!overridden) {
309 codeset = icodeset = loc_codeset;
310 free_codeset = 1;
311 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000312
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000313 /* Initialize Py_FileSystemDefaultEncoding from
314 locale even if PYTHONIOENCODING is set. */
315 if (!Py_FileSystemDefaultEncoding) {
316 Py_FileSystemDefaultEncoding = loc_codeset;
317 if (!overridden)
318 free_codeset = 0;
319 }
320 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000321#endif
322
323#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000324 if (!overridden) {
325 icodeset = ibuf;
326 codeset = buf;
327 sprintf(ibuf, "cp%d", GetConsoleCP());
328 sprintf(buf, "cp%d", GetConsoleOutputCP());
329 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000330#endif
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000331
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000332 if (codeset) {
333 sys_stream = PySys_GetObject("stdin");
334 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
335 if (!sys_isatty)
336 PyErr_Clear();
337 if ((overridden ||
338 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
339 PyFile_Check(sys_stream)) {
340 if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
341 Py_FatalError("Cannot set codeset of stdin");
342 }
343 Py_XDECREF(sys_isatty);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000344
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000345 sys_stream = PySys_GetObject("stdout");
346 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
347 if (!sys_isatty)
348 PyErr_Clear();
349 if ((overridden ||
350 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
351 PyFile_Check(sys_stream)) {
352 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
353 Py_FatalError("Cannot set codeset of stdout");
354 }
355 Py_XDECREF(sys_isatty);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000356
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000357 sys_stream = PySys_GetObject("stderr");
358 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
359 if (!sys_isatty)
360 PyErr_Clear();
361 if((overridden ||
362 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
363 PyFile_Check(sys_stream)) {
364 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
365 Py_FatalError("Cannot set codeset of stderr");
366 }
367 Py_XDECREF(sys_isatty);
Martin v. Löwisea62d252006-04-03 10:56:49 +0000368
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000369 if (free_codeset)
370 free(codeset);
371 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000372}
373
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000374void
375Py_Initialize(void)
376{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000377 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000378}
379
380
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000381#ifdef COUNT_ALLOCS
Martin v. Löwis45294a92006-04-18 06:24:08 +0000382extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000383#endif
384
Guido van Rossum25ce5661997-08-02 03:10:38 +0000385/* Undo the effect of Py_Initialize().
386
387 Beware: if multiple interpreter and/or thread states exist, these
388 are not wiped out; only the current thread and interpreter state
389 are deleted. But since everything else is deleted, those other
390 interpreter and thread states should no longer be used.
391
392 (XXX We should do better, e.g. wipe out all interpreters and
393 threads.)
394
395 Locking: as above.
396
397*/
398
399void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000400Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000401{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000402 PyInterpreterState *interp;
403 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000404
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000405 if (!initialized)
406 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000407
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000408 wait_for_thread_shutdown();
Antoine Pitrouefb60c02009-10-20 21:29:37 +0000409
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000410 /* The interpreter is still entirely intact at this point, and the
411 * exit funcs may be relying on that. In particular, if some thread
412 * or exit func is still waiting to do an import, the import machinery
413 * expects Py_IsInitialized() to return true. So don't say the
414 * interpreter is uninitialized until after the exit funcs have run.
415 * Note that Threading.py uses an exit func to do a join on all the
416 * threads created thru it, so this also protects pending imports in
417 * the threads created via Threading.
418 */
419 call_sys_exitfunc();
420 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000421
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000422 /* Get current thread state and interpreter pointer */
423 tstate = PyThreadState_GET();
424 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000425
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000426 /* Disable signal handling */
427 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000428
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000429 /* Clear type lookup cache */
430 PyType_ClearCache();
Christian Heimes908caac2008-01-27 23:34:59 +0000431
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000432 /* Collect garbage. This may call finalizers; it's nice to call these
433 * before all modules are destroyed.
434 * XXX If a __del__ or weakref callback is triggered here, and tries to
435 * XXX import a module, bad things can happen, because Python no
436 * XXX longer believes it's initialized.
437 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
438 * XXX is easy to provoke that way. I've also seen, e.g.,
439 * XXX Exception exceptions.ImportError: 'No module named sha'
440 * XXX in <function callback at 0x008F5718> ignored
441 * XXX but I'm unclear on exactly how that one happens. In any case,
442 * XXX I haven't seen a real-life report of either of these.
443 */
444 PyGC_Collect();
Martin v. Löwis45294a92006-04-18 06:24:08 +0000445#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000446 /* With COUNT_ALLOCS, it helps to run GC multiple times:
447 each collection might release some types from the type
448 list, so they become garbage. */
449 while (PyGC_Collect() > 0)
450 /* nothing */;
Martin v. Löwis45294a92006-04-18 06:24:08 +0000451#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000452
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000453 /* Destroy all modules */
454 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000455
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000456 /* Collect final garbage. This disposes of cycles created by
457 * new-style class definitions, for example.
458 * XXX This is disabled because it caused too many problems. If
459 * XXX a __del__ or weakref callback triggers here, Python code has
460 * XXX a hard time running, because even the sys module has been
461 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
462 * XXX One symptom is a sequence of information-free messages
463 * XXX coming from threads (if a __del__ or callback is invoked,
464 * XXX other threads can execute too, and any exception they encounter
465 * XXX triggers a comedy of errors as subsystem after subsystem
466 * XXX fails to find what it *expects* to find in sys to help report
467 * XXX the exception and consequent unexpected failures). I've also
468 * XXX seen segfaults then, after adding print statements to the
469 * XXX Python code getting called.
470 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000471#if 0
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000472 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000473#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000474
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000475 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
476 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000477
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000478 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000479#ifdef COUNT_ALLOCS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000480 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000481#endif
482
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000483 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000484
Tim Peters9cf25ce2003-04-17 15:21:01 +0000485#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000486 /* Display all objects still alive -- this can invoke arbitrary
487 * __repr__ overrides, so requires a mostly-intact interpreter.
488 * Alas, a lot of stuff may still be alive now that will be cleaned
489 * up later.
490 */
491 if (Py_GETENV("PYTHONDUMPREFS"))
492 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000493#endif /* Py_TRACE_REFS */
494
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000495 /* Clear interpreter state */
496 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000497
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000498 /* Now we decref the exception classes. After this point nothing
499 can raise an exception. That's okay, because each Fini() method
500 below has been checked to make sure no exceptions are ever
501 raised.
502 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000503
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000504 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000505
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000506 /* Cleanup auto-thread-state */
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000507#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000508 _PyGILState_Fini();
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000509#endif /* WITH_THREAD */
510
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000511 /* Delete current thread */
512 PyThreadState_Swap(NULL);
513 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000514
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000515 /* Sundry finalizers */
516 PyMethod_Fini();
517 PyFrame_Fini();
518 PyCFunction_Fini();
519 PyTuple_Fini();
520 PyList_Fini();
521 PySet_Fini();
522 PyString_Fini();
523 PyByteArray_Fini();
524 PyInt_Fini();
525 PyFloat_Fini();
526 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000527
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000528#ifdef Py_USING_UNICODE
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000529 /* Cleanup Unicode implementation */
530 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000531#endif
532
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000533 /* XXX Still allocated:
534 - various static ad-hoc pointers to interned strings
535 - int and float free list blocks
536 - whatever various modules and libraries allocate
537 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000539 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000540
Tim Peters269b2a62003-04-17 19:52:29 +0000541#ifdef Py_TRACE_REFS
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000542 /* Display addresses (& refcnts) of all objects still alive.
543 * An address can be used to find the repr of the object, printed
544 * above by _Py_PrintReferences.
545 */
546 if (Py_GETENV("PYTHONDUMPREFS"))
547 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000548#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000549#ifdef PYMALLOC_DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000550 if (Py_GETENV("PYTHONMALLOCSTATS"))
551 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000552#endif
553
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000554 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555}
556
557/* Create and initialize a new interpreter and thread, and return the
558 new thread. This requires that Py_Initialize() has been called
559 first.
560
561 Unsuccessful initialization yields a NULL pointer. Note that *no*
562 exception information is available even in this case -- the
563 exception information is held in the thread, and there is no
564 thread.
565
566 Locking: as above.
567
568*/
569
570PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000571Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000573 PyInterpreterState *interp;
574 PyThreadState *tstate, *save_tstate;
575 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000577 if (!initialized)
578 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000580 interp = PyInterpreterState_New();
581 if (interp == NULL)
582 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000583
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000584 tstate = PyThreadState_New(interp);
585 if (tstate == NULL) {
586 PyInterpreterState_Delete(interp);
587 return NULL;
588 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000590 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000592 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000593
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000594 interp->modules = PyDict_New();
595 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000597 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
598 if (bimod != NULL) {
599 interp->builtins = PyModule_GetDict(bimod);
600 if (interp->builtins == NULL)
601 goto handle_error;
602 Py_INCREF(interp->builtins);
603 }
604 sysmod = _PyImport_FindExtension("sys", "sys");
605 if (bimod != NULL && sysmod != NULL) {
606 interp->sysdict = PyModule_GetDict(sysmod);
607 if (interp->sysdict == NULL)
608 goto handle_error;
609 Py_INCREF(interp->sysdict);
610 PySys_SetPath(Py_GetPath());
611 PyDict_SetItemString(interp->sysdict, "modules",
612 interp->modules);
613 _PyImportHooks_Init();
614 initmain();
615 if (!Py_NoSiteFlag)
616 initsite();
617 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000618
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000619 if (!PyErr_Occurred())
620 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000622handle_error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000623 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000624
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000625 PyErr_Print();
626 PyThreadState_Clear(tstate);
627 PyThreadState_Swap(save_tstate);
628 PyThreadState_Delete(tstate);
629 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000631 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000632}
633
634/* Delete an interpreter and its last thread. This requires that the
635 given thread state is current, that the thread has no remaining
636 frames, and that it is its interpreter's only remaining thread.
637 It is a fatal error to violate these constraints.
638
639 (Py_Finalize() doesn't have these constraints -- it zaps
640 everything, regardless.)
641
642 Locking: as above.
643
644*/
645
646void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000647Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000648{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000649 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000650
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000651 if (tstate != PyThreadState_GET())
652 Py_FatalError("Py_EndInterpreter: thread is not current");
653 if (tstate->frame != NULL)
654 Py_FatalError("Py_EndInterpreter: thread still has a frame");
655 if (tstate != interp->tstate_head || tstate->next != NULL)
656 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000657
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000658 PyImport_Cleanup();
659 PyInterpreterState_Clear(interp);
660 PyThreadState_Swap(NULL);
661 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000662}
663
664static char *progname = "python";
665
666void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000667Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000668{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000669 if (pn && *pn)
670 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000671}
672
673char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000674Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000675{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000676 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000677}
678
Guido van Rossuma61691e1998-02-06 22:27:24 +0000679static char *default_home = NULL;
680
681void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000682Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000683{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000684 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000685}
686
687char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000688Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000689{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000690 char *home = default_home;
691 if (home == NULL && !Py_IgnoreEnvironmentFlag)
692 home = Py_GETENV("PYTHONHOME");
693 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000694}
695
Guido van Rossum6135a871995-01-09 17:53:26 +0000696/* Create __main__ module */
697
698static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000699initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000700{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000701 PyObject *m, *d;
702 m = PyImport_AddModule("__main__");
703 if (m == NULL)
704 Py_FatalError("can't create __main__ module");
705 d = PyModule_GetDict(m);
706 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
707 PyObject *bimod = PyImport_ImportModule("__builtin__");
708 if (bimod == NULL ||
709 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
710 Py_FatalError("can't add __builtins__ to __main__");
711 Py_XDECREF(bimod);
712 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000713}
714
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000715/* Import the site module (not into __main__ though) */
716
717static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000718initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000719{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000720 PyObject *m;
721 m = PyImport_ImportModule("site");
722 if (m == NULL) {
723 PyErr_Print();
724 Py_Finalize();
725 exit(1);
726 }
727 else {
728 Py_DECREF(m);
729 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000730}
731
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000732/* Parse input from a file and execute it */
733
734int
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000735PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000736 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000737{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000738 if (filename == NULL)
739 filename = "???";
740 if (Py_FdIsInteractive(fp, filename)) {
741 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
742 if (closeit)
743 fclose(fp);
744 return err;
745 }
746 else
747 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000748}
749
750int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000751PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000752{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000753 PyObject *v;
754 int ret;
755 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000756
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000757 if (flags == NULL) {
758 flags = &local_flags;
759 local_flags.cf_flags = 0;
760 }
761 v = PySys_GetObject("ps1");
762 if (v == NULL) {
763 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
764 Py_XDECREF(v);
765 }
766 v = PySys_GetObject("ps2");
767 if (v == NULL) {
768 PySys_SetObject("ps2", v = PyString_FromString("... "));
769 Py_XDECREF(v);
770 }
771 for (;;) {
772 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
773 PRINT_TOTAL_REFS();
774 if (ret == E_EOF)
775 return 0;
776 /*
777 if (ret == E_NOMEM)
778 return -1;
779 */
780 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000781}
782
Eric Smith7c478942008-03-18 23:45:49 +0000783#if 0
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000784/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000785#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000786 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
787 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Eric Smith7c478942008-03-18 23:45:49 +0000788#endif
789#if 1
Neal Norwitzca460d92006-09-06 06:28:06 +0000790/* Keep an example of flags with future keyword support. */
791#define PARSER_FLAGS(flags) \
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000792 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
793 PyPARSE_DONT_IMPLY_DEDENT : 0) \
794 | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
795 PyPARSE_PRINT_IS_FUNCTION : 0) \
796 | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
797 PyPARSE_UNICODE_LITERALS : 0) \
798 ) : 0)
Neal Norwitzca460d92006-09-06 06:28:06 +0000799#endif
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000800
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000801int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000802PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000803{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000804 PyObject *m, *d, *v, *w;
805 mod_ty mod;
806 PyArena *arena;
807 char *ps1 = "", *ps2 = "";
808 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000809
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000810 v = PySys_GetObject("ps1");
811 if (v != NULL) {
812 v = PyObject_Str(v);
813 if (v == NULL)
814 PyErr_Clear();
815 else if (PyString_Check(v))
816 ps1 = PyString_AsString(v);
817 }
818 w = PySys_GetObject("ps2");
819 if (w != NULL) {
820 w = PyObject_Str(w);
821 if (w == NULL)
822 PyErr_Clear();
823 else if (PyString_Check(w))
824 ps2 = PyString_AsString(w);
825 }
826 arena = PyArena_New();
827 if (arena == NULL) {
828 Py_XDECREF(v);
829 Py_XDECREF(w);
830 return -1;
831 }
832 mod = PyParser_ASTFromFile(fp, filename,
833 Py_single_input, ps1, ps2,
834 flags, &errcode, arena);
835 Py_XDECREF(v);
836 Py_XDECREF(w);
837 if (mod == NULL) {
838 PyArena_Free(arena);
839 if (errcode == E_EOF) {
840 PyErr_Clear();
841 return E_EOF;
842 }
843 PyErr_Print();
844 return -1;
845 }
846 m = PyImport_AddModule("__main__");
847 if (m == NULL) {
848 PyArena_Free(arena);
849 return -1;
850 }
851 d = PyModule_GetDict(m);
852 v = run_mod(mod, filename, d, d, flags, arena);
853 PyArena_Free(arena);
854 if (v == NULL) {
855 PyErr_Print();
856 return -1;
857 }
858 Py_DECREF(v);
859 if (Py_FlushLine())
860 PyErr_Clear();
861 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000862}
863
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000864/* Check whether a file maybe a pyc file: Look at the extension,
865 the file type, and, if we may close it, at the first few bytes. */
866
867static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000868maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000869{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000870 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
871 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000872
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000873 /* Only look into the file if we are allowed to close it, since
874 it then should also be seekable. */
875 if (closeit) {
876 /* Read only two bytes of the magic. If the file was opened in
877 text mode, the bytes 3 and 4 of the magic (\r\n) might not
878 be read as they are on disk. */
879 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
880 unsigned char buf[2];
881 /* Mess: In case of -x, the stream is NOT at its start now,
882 and ungetc() was used to push back the first newline,
883 which makes the current stream position formally undefined,
884 and a x-platform nightmare.
885 Unfortunately, we have no direct way to know whether -x
886 was specified. So we use a terrible hack: if the current
887 stream position is not 0, we assume -x was specified, and
888 give up. Bug 132850 on SourceForge spells out the
889 hopelessness of trying anything else (fseek and ftell
890 don't work predictably x-platform for text-mode files).
891 */
892 int ispyc = 0;
893 if (ftell(fp) == 0) {
894 if (fread(buf, 1, 2, fp) == 2 &&
895 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
896 ispyc = 1;
897 rewind(fp);
898 }
899 return ispyc;
900 }
901 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000902}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000903
Guido van Rossum0df002c2000-08-27 19:21:52 +0000904int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000905PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000906 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000907{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000908 PyObject *m, *d, *v;
909 const char *ext;
910 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000911
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000912 m = PyImport_AddModule("__main__");
913 if (m == NULL)
914 return -1;
915 d = PyModule_GetDict(m);
916 if (PyDict_GetItemString(d, "__file__") == NULL) {
917 PyObject *f = PyString_FromString(filename);
918 if (f == NULL)
919 return -1;
920 if (PyDict_SetItemString(d, "__file__", f) < 0) {
921 Py_DECREF(f);
922 return -1;
923 }
924 set_file_name = 1;
925 Py_DECREF(f);
926 }
927 len = strlen(filename);
928 ext = filename + len - (len > 4 ? 4 : 0);
929 if (maybe_pyc_file(fp, filename, ext, closeit)) {
930 /* Try to run a pyc file. First, re-open in binary */
931 if (closeit)
932 fclose(fp);
933 if ((fp = fopen(filename, "rb")) == NULL) {
934 fprintf(stderr, "python: Can't reopen .pyc file\n");
935 ret = -1;
936 goto done;
937 }
938 /* Turn on optimization if a .pyo file is given */
939 if (strcmp(ext, ".pyo") == 0)
940 Py_OptimizeFlag = 1;
941 v = run_pyc_file(fp, filename, d, d, flags);
942 } else {
943 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
944 closeit, flags);
945 }
946 if (v == NULL) {
947 PyErr_Print();
948 ret = -1;
949 goto done;
950 }
951 Py_DECREF(v);
952 if (Py_FlushLine())
953 PyErr_Clear();
954 ret = 0;
Georg Brandlaa2321b2007-03-07 00:40:28 +0000955 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000956 if (set_file_name && PyDict_DelItemString(d, "__file__"))
957 PyErr_Clear();
958 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000959}
960
961int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000962PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000963{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000964 PyObject *m, *d, *v;
965 m = PyImport_AddModule("__main__");
966 if (m == NULL)
967 return -1;
968 d = PyModule_GetDict(m);
969 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
970 if (v == NULL) {
971 PyErr_Print();
972 return -1;
973 }
974 Py_DECREF(v);
975 if (Py_FlushLine())
976 PyErr_Clear();
977 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000978}
979
Barry Warsaw035574d1997-08-29 22:07:17 +0000980static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000981parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000982 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000983{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000984 long hold;
985 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +0000986
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000987 /* old style errors */
988 if (PyTuple_Check(err))
989 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
990 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000991
Benjamin Petersonb9348e72012-04-03 00:30:38 -0400992 *message = NULL;
993
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000994 /* new style errors. `err' is an instance */
Benjamin Petersonb9348e72012-04-03 00:30:38 -0400995 *message = PyObject_GetAttrString(err, "msg");
996 if (!*message)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000997 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +0000998
Benjamin Petersonb9348e72012-04-03 00:30:38 -0400999 v = PyObject_GetAttrString(err, "filename");
1000 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001001 goto finally;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001002 if (v == Py_None) {
1003 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001004 *filename = NULL;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001005 }
1006 else {
1007 *filename = PyString_AsString(v);
1008 Py_DECREF(v);
1009 if (!*filename)
1010 goto finally;
1011 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001012
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001013 v = PyObject_GetAttrString(err, "lineno");
1014 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 goto finally;
1016 hold = PyInt_AsLong(v);
1017 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001018 if (hold < 0 && PyErr_Occurred())
1019 goto finally;
1020 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001021
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001022 v = PyObject_GetAttrString(err, "offset");
1023 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001024 goto finally;
1025 if (v == Py_None) {
1026 *offset = -1;
1027 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001028 } else {
1029 hold = PyInt_AsLong(v);
1030 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001031 if (hold < 0 && PyErr_Occurred())
1032 goto finally;
1033 *offset = (int)hold;
1034 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001035
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001036 v = PyObject_GetAttrString(err, "text");
1037 if (!v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001038 goto finally;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001039 if (v == Py_None) {
1040 Py_DECREF(v);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001041 *text = NULL;
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001042 }
1043 else {
1044 *text = PyString_AsString(v);
1045 Py_DECREF(v);
1046 if (!*text)
1047 goto finally;
1048 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001049 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001050
1051finally:
Benjamin Petersonb9348e72012-04-03 00:30:38 -04001052 Py_XDECREF(*message);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001053 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001054}
1055
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001056void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001057PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001058{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001059 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001060}
1061
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001062static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001063print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001064{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001065 char *nl;
1066 if (offset >= 0) {
Benjamin Petersonec9f9f52010-10-29 03:45:34 +00001067 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1068 offset--;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001069 for (;;) {
1070 nl = strchr(text, '\n');
1071 if (nl == NULL || nl-text >= offset)
1072 break;
1073 offset -= (int)(nl+1-text);
1074 text = nl+1;
1075 }
1076 while (*text == ' ' || *text == '\t') {
1077 text++;
1078 offset--;
1079 }
1080 }
1081 PyFile_WriteString(" ", f);
1082 PyFile_WriteString(text, f);
1083 if (*text == '\0' || text[strlen(text)-1] != '\n')
1084 PyFile_WriteString("\n", f);
1085 if (offset == -1)
1086 return;
1087 PyFile_WriteString(" ", f);
1088 offset--;
1089 while (offset > 0) {
1090 PyFile_WriteString(" ", f);
1091 offset--;
1092 }
1093 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001094}
1095
Guido van Rossum66e8e862001-03-23 17:54:43 +00001096static void
1097handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001098{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001099 PyObject *exception, *value, *tb;
1100 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001101
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001102 if (Py_InspectFlag)
1103 /* Don't exit if -i flag was given. This flag is set to 0
1104 * when entering interactive mode for inspecting. */
1105 return;
Georg Brandl49aafc92007-03-07 00:34:46 +00001106
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001107 PyErr_Fetch(&exception, &value, &tb);
1108 if (Py_FlushLine())
1109 PyErr_Clear();
1110 fflush(stdout);
1111 if (value == NULL || value == Py_None)
1112 goto done;
1113 if (PyExceptionInstance_Check(value)) {
1114 /* The error code should be in the `code' attribute. */
1115 PyObject *code = PyObject_GetAttrString(value, "code");
1116 if (code) {
1117 Py_DECREF(value);
1118 value = code;
1119 if (value == Py_None)
1120 goto done;
1121 }
1122 /* If we failed to dig out the 'code' attribute,
1123 just let the else clause below print the error. */
1124 }
1125 if (PyInt_Check(value))
1126 exitcode = (int)PyInt_AsLong(value);
1127 else {
Victor Stinnerc49dfcc2010-05-25 22:30:32 +00001128 PyObject *sys_stderr = PySys_GetObject("stderr");
1129 if (sys_stderr != NULL && sys_stderr != Py_None) {
1130 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1131 } else {
1132 PyObject_Print(value, stderr, Py_PRINT_RAW);
1133 fflush(stderr);
1134 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001135 PySys_WriteStderr("\n");
1136 exitcode = 1;
1137 }
Tim Peterscf615b52003-04-19 18:47:02 +00001138 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001139 /* Restore and clear the exception info, in order to properly decref
1140 * the exception, value, and traceback. If we just exit instead,
1141 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1142 * some finalizers from running.
1143 */
1144 PyErr_Restore(exception, value, tb);
1145 PyErr_Clear();
1146 Py_Exit(exitcode);
1147 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001148}
1149
1150void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001151PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001152{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001153 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001154
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001155 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1156 handle_system_exit();
1157 }
1158 PyErr_Fetch(&exception, &v, &tb);
1159 if (exception == NULL)
1160 return;
1161 PyErr_NormalizeException(&exception, &v, &tb);
1162 if (exception == NULL)
1163 return;
1164 /* Now we know v != NULL too */
1165 if (set_sys_last_vars) {
1166 PySys_SetObject("last_type", exception);
1167 PySys_SetObject("last_value", v);
1168 PySys_SetObject("last_traceback", tb);
1169 }
1170 hook = PySys_GetObject("excepthook");
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001171 if (hook && hook != Py_None) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001172 PyObject *args = PyTuple_Pack(3,
1173 exception, v, tb ? tb : Py_None);
1174 PyObject *result = PyEval_CallObject(hook, args);
1175 if (result == NULL) {
1176 PyObject *exception2, *v2, *tb2;
1177 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1178 handle_system_exit();
1179 }
1180 PyErr_Fetch(&exception2, &v2, &tb2);
1181 PyErr_NormalizeException(&exception2, &v2, &tb2);
1182 /* It should not be possible for exception2 or v2
1183 to be NULL. However PyErr_Display() can't
1184 tolerate NULLs, so just be safe. */
1185 if (exception2 == NULL) {
1186 exception2 = Py_None;
1187 Py_INCREF(exception2);
1188 }
1189 if (v2 == NULL) {
1190 v2 = Py_None;
1191 Py_INCREF(v2);
1192 }
1193 if (Py_FlushLine())
1194 PyErr_Clear();
1195 fflush(stdout);
1196 PySys_WriteStderr("Error in sys.excepthook:\n");
1197 PyErr_Display(exception2, v2, tb2);
1198 PySys_WriteStderr("\nOriginal exception was:\n");
1199 PyErr_Display(exception, v, tb);
1200 Py_DECREF(exception2);
1201 Py_DECREF(v2);
1202 Py_XDECREF(tb2);
1203 }
1204 Py_XDECREF(result);
1205 Py_XDECREF(args);
1206 } else {
1207 PySys_WriteStderr("sys.excepthook is missing\n");
1208 PyErr_Display(exception, v, tb);
1209 }
1210 Py_XDECREF(exception);
1211 Py_XDECREF(v);
1212 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001213}
1214
Richard Jones7b9558d2006-05-27 12:29:24 +00001215void
1216PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001217{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001218 int err = 0;
1219 PyObject *f = PySys_GetObject("stderr");
1220 Py_INCREF(value);
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001221 if (f == NULL || f == Py_None)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001222 fprintf(stderr, "lost sys.stderr\n");
1223 else {
1224 if (Py_FlushLine())
1225 PyErr_Clear();
1226 fflush(stdout);
1227 if (tb && tb != Py_None)
1228 err = PyTraceBack_Print(tb, f);
1229 if (err == 0 &&
1230 PyObject_HasAttrString(value, "print_file_and_line"))
1231 {
1232 PyObject *message;
1233 const char *filename, *text;
1234 int lineno, offset;
1235 if (!parse_syntax_error(value, &message, &filename,
1236 &lineno, &offset, &text))
1237 PyErr_Clear();
1238 else {
1239 char buf[10];
1240 PyFile_WriteString(" File \"", f);
1241 if (filename == NULL)
1242 PyFile_WriteString("<string>", f);
1243 else
1244 PyFile_WriteString(filename, f);
1245 PyFile_WriteString("\", line ", f);
1246 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1247 PyFile_WriteString(buf, f);
1248 PyFile_WriteString("\n", f);
1249 if (text != NULL)
1250 print_error_text(f, offset, text);
1251 Py_DECREF(value);
1252 value = message;
1253 /* Can't be bothered to check all those
1254 PyFile_WriteString() calls */
1255 if (PyErr_Occurred())
1256 err = -1;
1257 }
1258 }
1259 if (err) {
1260 /* Don't do anything else */
1261 }
1262 else if (PyExceptionClass_Check(exception)) {
1263 PyObject* moduleName;
1264 char* className = PyExceptionClass_Name(exception);
1265 if (className != NULL) {
1266 char *dot = strrchr(className, '.');
1267 if (dot != NULL)
1268 className = dot+1;
1269 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001270
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001271 moduleName = PyObject_GetAttrString(exception, "__module__");
1272 if (moduleName == NULL)
1273 err = PyFile_WriteString("<unknown>", f);
1274 else {
1275 char* modstr = PyString_AsString(moduleName);
1276 if (modstr && strcmp(modstr, "exceptions"))
1277 {
1278 err = PyFile_WriteString(modstr, f);
1279 err += PyFile_WriteString(".", f);
1280 }
1281 Py_DECREF(moduleName);
1282 }
1283 if (err == 0) {
1284 if (className == NULL)
1285 err = PyFile_WriteString("<unknown>", f);
1286 else
1287 err = PyFile_WriteString(className, f);
1288 }
1289 }
1290 else
1291 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1292 if (err == 0 && (value != Py_None)) {
1293 PyObject *s = PyObject_Str(value);
1294 /* only print colon if the str() of the
1295 object is not the empty string
1296 */
1297 if (s == NULL)
1298 err = -1;
1299 else if (!PyString_Check(s) ||
1300 PyString_GET_SIZE(s) != 0)
1301 err = PyFile_WriteString(": ", f);
1302 if (err == 0)
1303 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1304 Py_XDECREF(s);
1305 }
1306 /* try to write a newline in any case */
1307 err += PyFile_WriteString("\n", f);
1308 }
1309 Py_DECREF(value);
1310 /* If an error happened here, don't show it.
1311 XXX This is wrong, but too many callers rely on this behavior. */
1312 if (err != 0)
1313 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001314}
1315
Guido van Rossum82598051997-03-05 00:20:32 +00001316PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001317PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001318 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001319{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001320 PyObject *ret = NULL;
1321 mod_ty mod;
1322 PyArena *arena = PyArena_New();
1323 if (arena == NULL)
1324 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001325
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001326 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1327 if (mod != NULL)
1328 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1329 PyArena_Free(arena);
1330 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001331}
1332
1333PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001334PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001335 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001336{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001337 PyObject *ret;
1338 mod_ty mod;
1339 PyArena *arena = PyArena_New();
1340 if (arena == NULL)
1341 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001342
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001343 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1344 flags, NULL, arena);
1345 if (closeit)
1346 fclose(fp);
1347 if (mod == NULL) {
1348 PyArena_Free(arena);
1349 return NULL;
1350 }
1351 ret = run_mod(mod, filename, globals, locals, flags, arena);
1352 PyArena_Free(arena);
1353 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001354}
1355
Guido van Rossum82598051997-03-05 00:20:32 +00001356static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001357run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001358 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001359{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001360 PyCodeObject *co;
1361 PyObject *v;
1362 co = PyAST_Compile(mod, filename, flags, arena);
1363 if (co == NULL)
1364 return NULL;
1365 v = PyEval_EvalCode(co, globals, locals);
1366 Py_DECREF(co);
1367 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001368}
1369
Guido van Rossum82598051997-03-05 00:20:32 +00001370static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001371run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001372 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001373{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001374 PyCodeObject *co;
1375 PyObject *v;
1376 long magic;
1377 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001378
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001379 magic = PyMarshal_ReadLongFromFile(fp);
1380 if (magic != PyImport_GetMagicNumber()) {
1381 PyErr_SetString(PyExc_RuntimeError,
1382 "Bad magic number in .pyc file");
1383 return NULL;
1384 }
1385 (void) PyMarshal_ReadLongFromFile(fp);
1386 v = PyMarshal_ReadLastObjectFromFile(fp);
1387 fclose(fp);
1388 if (v == NULL || !PyCode_Check(v)) {
1389 Py_XDECREF(v);
1390 PyErr_SetString(PyExc_RuntimeError,
1391 "Bad code object in .pyc file");
1392 return NULL;
1393 }
1394 co = (PyCodeObject *)v;
1395 v = PyEval_EvalCode(co, globals, locals);
1396 if (v && flags)
1397 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1398 Py_DECREF(co);
1399 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001400}
1401
Guido van Rossum82598051997-03-05 00:20:32 +00001402PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001403Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001404 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001405{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001406 PyCodeObject *co;
1407 mod_ty mod;
1408 PyArena *arena = PyArena_New();
1409 if (arena == NULL)
1410 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001411
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001412 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1413 if (mod == NULL) {
1414 PyArena_Free(arena);
1415 return NULL;
1416 }
1417 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1418 PyObject *result = PyAST_mod2obj(mod);
1419 PyArena_Free(arena);
1420 return result;
1421 }
1422 co = PyAST_Compile(mod, filename, flags, arena);
1423 PyArena_Free(arena);
1424 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001425}
1426
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001427struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001428Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001429{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001430 struct symtable *st;
1431 mod_ty mod;
1432 PyCompilerFlags flags;
1433 PyArena *arena = PyArena_New();
1434 if (arena == NULL)
1435 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001436
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001437 flags.cf_flags = 0;
Christian Heimes7f23d862008-03-26 22:51:58 +00001438
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001439 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1440 if (mod == NULL) {
1441 PyArena_Free(arena);
1442 return NULL;
1443 }
1444 st = PySymtable_Build(mod, filename, 0);
1445 PyArena_Free(arena);
1446 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001447}
1448
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001449/* Preferred access to parser is through AST. */
1450mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001451PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001452 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001454 mod_ty mod;
1455 PyCompilerFlags localflags;
1456 perrdetail err;
1457 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001458
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001459 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1460 &_PyParser_Grammar, start, &err,
1461 &iflags);
1462 if (flags == NULL) {
1463 localflags.cf_flags = 0;
1464 flags = &localflags;
1465 }
1466 if (n) {
1467 flags->cf_flags |= iflags & PyCF_MASK;
1468 mod = PyAST_FromNode(n, flags, filename, arena);
1469 PyNode_Free(n);
1470 return mod;
1471 }
1472 else {
1473 err_input(&err);
1474 return NULL;
1475 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476}
1477
1478mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001479PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001480 char *ps2, PyCompilerFlags *flags, int *errcode,
1481 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001482{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001483 mod_ty mod;
1484 PyCompilerFlags localflags;
1485 perrdetail err;
1486 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001487
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001488 node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
1489 start, ps1, ps2, &err, &iflags);
1490 if (flags == NULL) {
1491 localflags.cf_flags = 0;
1492 flags = &localflags;
1493 }
1494 if (n) {
1495 flags->cf_flags |= iflags & PyCF_MASK;
1496 mod = PyAST_FromNode(n, flags, filename, arena);
1497 PyNode_Free(n);
1498 return mod;
1499 }
1500 else {
1501 err_input(&err);
1502 if (errcode)
1503 *errcode = err.error;
1504 return NULL;
1505 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506}
1507
Guido van Rossuma110aa61994-08-29 12:50:44 +00001508/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001509
Guido van Rossuma110aa61994-08-29 12:50:44 +00001510node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001511PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001512{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001513 perrdetail err;
1514 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1515 start, NULL, NULL, &err, flags);
1516 if (n == NULL)
1517 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001518
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001519 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001520}
1521
Guido van Rossuma110aa61994-08-29 12:50:44 +00001522/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001523
Guido van Rossuma110aa61994-08-29 12:50:44 +00001524node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001525PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001526{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001527 perrdetail err;
1528 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1529 start, &err, flags);
1530 if (n == NULL)
1531 err_input(&err);
1532 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001533}
1534
1535node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001536PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001537 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001538{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001539 perrdetail err;
1540 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1541 &_PyParser_Grammar, start, &err, flags);
1542 if (n == NULL)
1543 err_input(&err);
1544 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001545}
1546
1547node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001548PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001549{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001550 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001551}
1552
Guido van Rossum66ebd912003-04-17 16:02:26 +00001553/* May want to move a more generalized form of this to parsetok.c or
1554 even parser modules. */
1555
1556void
1557PyParser_SetError(perrdetail *err)
1558{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001559 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001560}
1561
Guido van Rossuma110aa61994-08-29 12:50:44 +00001562/* Set the error appropriate to the given input error code (see errcode.h) */
1563
1564static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001565err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001566{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001567 PyObject *v, *w, *errtype;
1568 PyObject* u = NULL;
1569 char *msg = NULL;
1570 errtype = PyExc_SyntaxError;
1571 switch (err->error) {
1572 case E_ERROR:
1573 return;
1574 case E_SYNTAX:
1575 errtype = PyExc_IndentationError;
1576 if (err->expected == INDENT)
1577 msg = "expected an indented block";
1578 else if (err->token == INDENT)
1579 msg = "unexpected indent";
1580 else if (err->token == DEDENT)
1581 msg = "unexpected unindent";
1582 else {
1583 errtype = PyExc_SyntaxError;
1584 msg = "invalid syntax";
1585 }
1586 break;
1587 case E_TOKEN:
1588 msg = "invalid token";
1589 break;
1590 case E_EOFS:
1591 msg = "EOF while scanning triple-quoted string literal";
1592 break;
1593 case E_EOLS:
1594 msg = "EOL while scanning string literal";
1595 break;
1596 case E_INTR:
1597 if (!PyErr_Occurred())
1598 PyErr_SetNone(PyExc_KeyboardInterrupt);
1599 goto cleanup;
1600 case E_NOMEM:
1601 PyErr_NoMemory();
1602 goto cleanup;
1603 case E_EOF:
1604 msg = "unexpected EOF while parsing";
1605 break;
1606 case E_TABSPACE:
1607 errtype = PyExc_TabError;
1608 msg = "inconsistent use of tabs and spaces in indentation";
1609 break;
1610 case E_OVERFLOW:
1611 msg = "expression too long";
1612 break;
1613 case E_DEDENT:
1614 errtype = PyExc_IndentationError;
1615 msg = "unindent does not match any outer indentation level";
1616 break;
1617 case E_TOODEEP:
1618 errtype = PyExc_IndentationError;
1619 msg = "too many levels of indentation";
1620 break;
1621 case E_DECODE: {
1622 PyObject *type, *value, *tb;
1623 PyErr_Fetch(&type, &value, &tb);
1624 if (value != NULL) {
1625 u = PyObject_Str(value);
1626 if (u != NULL) {
1627 msg = PyString_AsString(u);
1628 }
1629 }
1630 if (msg == NULL)
1631 msg = "unknown decode error";
1632 Py_XDECREF(type);
1633 Py_XDECREF(value);
1634 Py_XDECREF(tb);
1635 break;
1636 }
1637 case E_LINECONT:
1638 msg = "unexpected character after line continuation character";
1639 break;
1640 default:
1641 fprintf(stderr, "error=%d\n", err->error);
1642 msg = "unknown parsing error";
1643 break;
1644 }
1645 v = Py_BuildValue("(ziiz)", err->filename,
1646 err->lineno, err->offset, err->text);
1647 w = NULL;
1648 if (v != NULL)
1649 w = Py_BuildValue("(sO)", msg, v);
1650 Py_XDECREF(u);
1651 Py_XDECREF(v);
1652 PyErr_SetObject(errtype, w);
1653 Py_XDECREF(w);
Georg Brandl1ad108d2008-07-19 10:08:55 +00001654cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001655 if (err->text != NULL) {
1656 PyObject_FREE(err->text);
1657 err->text = NULL;
1658 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001659}
1660
1661/* Print fatal error message and abort */
1662
1663void
Tim Peters7c321a82002-07-09 02:57:01 +00001664Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001665{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001666 fprintf(stderr, "Fatal Python error: %s\n", msg);
1667 fflush(stderr); /* it helps in Windows debug build */
Jesse Noller42f9b4e2009-03-31 22:20:35 +00001668
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001669#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001670 {
1671 size_t len = strlen(msg);
1672 WCHAR* buffer;
1673 size_t i;
Martin v. Löwis5344c992009-01-02 20:32:55 +00001674
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001675 /* Convert the message to wchar_t. This uses a simple one-to-one
1676 conversion, assuming that the this error message actually uses ASCII
1677 only. If this ceases to be true, we will have to convert. */
1678 buffer = alloca( (len+1) * (sizeof *buffer));
1679 for( i=0; i<=len; ++i)
1680 buffer[i] = msg[i];
1681 OutputDebugStringW(L"Fatal Python error: ");
1682 OutputDebugStringW(buffer);
1683 OutputDebugStringW(L"\n");
1684 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001685#ifdef _DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001686 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001687#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001688#endif /* MS_WINDOWS */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001689 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001690}
1691
1692/* Clean up and exit */
1693
Guido van Rossuma110aa61994-08-29 12:50:44 +00001694#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001695#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001696#endif
1697
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001698/* Wait until threading._shutdown completes, provided
1699 the threading module was imported in the first place.
1700 The shutdown routine will wait until all non-daemon
1701 "threading" threads have completed. */
1702static void
1703wait_for_thread_shutdown(void)
1704{
1705#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001706 PyObject *result;
1707 PyThreadState *tstate = PyThreadState_GET();
1708 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1709 "threading");
1710 if (threading == NULL) {
1711 /* threading not imported */
1712 PyErr_Clear();
1713 return;
1714 }
1715 result = PyObject_CallMethod(threading, "_shutdown", "");
1716 if (result == NULL)
1717 PyErr_WriteUnraisable(threading);
1718 else
1719 Py_DECREF(result);
1720 Py_DECREF(threading);
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001721#endif
1722}
1723
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001724#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001725static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001726static int nexitfuncs = 0;
1727
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001728int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001729{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001730 if (nexitfuncs >= NEXITFUNCS)
1731 return -1;
1732 exitfuncs[nexitfuncs++] = func;
1733 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00001734}
1735
Guido van Rossumcc283f51997-08-05 02:22:03 +00001736static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001737call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001738{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001739 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001740
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001741 if (exitfunc) {
1742 PyObject *res;
1743 Py_INCREF(exitfunc);
1744 PySys_SetObject("exitfunc", (PyObject *)NULL);
1745 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1746 if (res == NULL) {
1747 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1748 PySys_WriteStderr("Error in sys.exitfunc:\n");
1749 }
1750 PyErr_Print();
1751 }
1752 Py_DECREF(exitfunc);
1753 }
Guido van Rossum59bff391992-09-03 20:28:00 +00001754
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001755 if (Py_FlushLine())
1756 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001757}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001758
Guido van Rossumcc283f51997-08-05 02:22:03 +00001759static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001760call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001761{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001762 while (nexitfuncs > 0)
1763 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001764
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001765 fflush(stdout);
1766 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001767}
1768
1769void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001770Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001771{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001772 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001773
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001774 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001775}
1776
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001777static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001778initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001779{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001780#ifdef SIGPIPE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001781 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001782#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001783#ifdef SIGXFZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001784 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001785#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001786#ifdef SIGXFSZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001787 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001788#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001789 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001790}
1791
Guido van Rossum7433b121997-02-14 19:45:36 +00001792
1793/*
1794 * The file descriptor fd is considered ``interactive'' if either
1795 * a) isatty(fd) is TRUE, or
1796 * b) the -i flag was given, and the filename associated with
1797 * the descriptor is NULL or "<stdin>" or "???".
1798 */
1799int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001800Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001801{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001802 if (isatty((int)fileno(fp)))
1803 return 1;
1804 if (!Py_InteractiveFlag)
1805 return 0;
1806 return (filename == NULL) ||
1807 (strcmp(filename, "<stdin>") == 0) ||
1808 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00001809}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001810
1811
Tim Petersd08e3822003-04-17 15:24:21 +00001812#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001813#if defined(WIN32) && defined(_MSC_VER)
1814
1815/* Stack checking for Microsoft C */
1816
1817#include <malloc.h>
1818#include <excpt.h>
1819
Fred Drakee8de31c2000-08-31 05:38:39 +00001820/*
1821 * Return non-zero when we run out of memory on the stack; zero otherwise.
1822 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001823int
Fred Drake399739f2000-08-31 05:52:44 +00001824PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001825{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001826 __try {
1827 /* alloca throws a stack overflow exception if there's
1828 not enough space left on the stack */
1829 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1830 return 0;
1831 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1832 EXCEPTION_EXECUTE_HANDLER :
1833 EXCEPTION_CONTINUE_SEARCH) {
1834 int errcode = _resetstkoflw();
1835 if (errcode == 0)
1836 {
1837 Py_FatalError("Could not reset the stack!");
1838 }
1839 }
1840 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001841}
1842
1843#endif /* WIN32 && _MSC_VER */
1844
1845/* Alternate implementations can be added here... */
1846
1847#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001848
1849
1850/* Wrappers around sigaction() or signal(). */
1851
1852PyOS_sighandler_t
1853PyOS_getsig(int sig)
1854{
1855#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001856 struct sigaction context;
1857 if (sigaction(sig, NULL, &context) == -1)
1858 return SIG_ERR;
1859 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001860#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001861 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001862/* Special signal handling for the secure CRT in Visual Studio 2005 */
1863#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001864 switch (sig) {
1865 /* Only these signals are valid */
1866 case SIGINT:
1867 case SIGILL:
1868 case SIGFPE:
1869 case SIGSEGV:
1870 case SIGTERM:
1871 case SIGBREAK:
1872 case SIGABRT:
1873 break;
1874 /* Don't call signal() with other values or it will assert */
1875 default:
1876 return SIG_ERR;
1877 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001878#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001879 handler = signal(sig, SIG_IGN);
1880 if (handler != SIG_ERR)
1881 signal(sig, handler);
1882 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001883#endif
1884}
1885
1886PyOS_sighandler_t
1887PyOS_setsig(int sig, PyOS_sighandler_t handler)
1888{
1889#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001890 /* Some code in Modules/signalmodule.c depends on sigaction() being
1891 * used here if HAVE_SIGACTION is defined. Fix that if this code
1892 * changes to invalidate that assumption.
1893 */
1894 struct sigaction context, ocontext;
1895 context.sa_handler = handler;
1896 sigemptyset(&context.sa_mask);
1897 context.sa_flags = 0;
1898 if (sigaction(sig, &context, &ocontext) == -1)
1899 return SIG_ERR;
1900 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001901#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001902 PyOS_sighandler_t oldhandler;
1903 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001904#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001905 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001906#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001907 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001908#endif
1909}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910
1911/* Deprecated C API functions still provided for binary compatiblity */
1912
1913#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001914PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001915PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1916{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001917 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918}
1919
Thomas Heller1b046642006-04-18 18:51:06 +00001920#undef PyParser_SimpleParseString
1921PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001922PyParser_SimpleParseString(const char *str, int start)
1923{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001924 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001925}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001926
Thomas Heller1b046642006-04-18 18:51:06 +00001927#undef PyRun_AnyFile
1928PyAPI_FUNC(int)
1929PyRun_AnyFile(FILE *fp, const char *name)
1930{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001931 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001932}
1933
1934#undef PyRun_AnyFileEx
1935PyAPI_FUNC(int)
1936PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1937{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001938 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001939}
1940
1941#undef PyRun_AnyFileFlags
1942PyAPI_FUNC(int)
1943PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1944{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001945 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001946}
1947
1948#undef PyRun_File
1949PyAPI_FUNC(PyObject *)
1950PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1951{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001952 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001953}
1954
1955#undef PyRun_FileEx
1956PyAPI_FUNC(PyObject *)
1957PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1958{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001959 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001960}
1961
1962#undef PyRun_FileFlags
1963PyAPI_FUNC(PyObject *)
1964PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001965 PyCompilerFlags *flags)
Thomas Heller1b046642006-04-18 18:51:06 +00001966{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001967 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001968}
1969
1970#undef PyRun_SimpleFile
1971PyAPI_FUNC(int)
1972PyRun_SimpleFile(FILE *f, const char *p)
1973{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001974 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001975}
1976
1977#undef PyRun_SimpleFileEx
1978PyAPI_FUNC(int)
1979PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1980{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001981 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001982}
1983
1984
1985#undef PyRun_String
1986PyAPI_FUNC(PyObject *)
1987PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1988{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001989 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001990}
1991
1992#undef PyRun_SimpleString
1993PyAPI_FUNC(int)
1994PyRun_SimpleString(const char *s)
1995{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001996 return PyRun_SimpleStringFlags(s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001997}
1998
1999#undef Py_CompileString
2000PyAPI_FUNC(PyObject *)
2001Py_CompileString(const char *str, const char *p, int s)
2002{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002003 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002004}
2005
2006#undef PyRun_InteractiveOne
2007PyAPI_FUNC(int)
2008PyRun_InteractiveOne(FILE *f, const char *p)
2009{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002010 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002011}
2012
2013#undef PyRun_InteractiveLoop
2014PyAPI_FUNC(int)
2015PyRun_InteractiveLoop(FILE *f, const char *p)
2016{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002017 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002018}
2019
Anthony Baxterac6bd462006-04-13 02:06:09 +00002020#ifdef __cplusplus
2021}
2022#endif
2023