blob: dcb2c0ebcc283d98393ece0e5b8baecb24c1a46f [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
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000992 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +0000993
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000994 if (! (v = PyObject_GetAttrString(err, "msg")))
995 goto finally;
996 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +0000997
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000998 if (!(v = PyObject_GetAttrString(err, "filename")))
999 goto finally;
1000 if (v == Py_None)
1001 *filename = NULL;
1002 else if (! (*filename = PyString_AsString(v)))
1003 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001004
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001005 Py_DECREF(v);
1006 if (!(v = PyObject_GetAttrString(err, "lineno")))
1007 goto finally;
1008 hold = PyInt_AsLong(v);
1009 Py_DECREF(v);
1010 v = NULL;
1011 if (hold < 0 && PyErr_Occurred())
1012 goto finally;
1013 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001014
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001015 if (!(v = PyObject_GetAttrString(err, "offset")))
1016 goto finally;
1017 if (v == Py_None) {
1018 *offset = -1;
1019 Py_DECREF(v);
1020 v = NULL;
1021 } else {
1022 hold = PyInt_AsLong(v);
1023 Py_DECREF(v);
1024 v = NULL;
1025 if (hold < 0 && PyErr_Occurred())
1026 goto finally;
1027 *offset = (int)hold;
1028 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001029
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001030 if (!(v = PyObject_GetAttrString(err, "text")))
1031 goto finally;
1032 if (v == Py_None)
1033 *text = NULL;
1034 else if (! (*text = PyString_AsString(v)))
1035 goto finally;
1036 Py_DECREF(v);
1037 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001038
1039finally:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001040 Py_XDECREF(v);
1041 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001042}
1043
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001044void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001045PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001046{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001047 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001048}
1049
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001050static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001051print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001052{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001053 char *nl;
1054 if (offset >= 0) {
Benjamin Petersonec9f9f52010-10-29 03:45:34 +00001055 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1056 offset--;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001057 for (;;) {
1058 nl = strchr(text, '\n');
1059 if (nl == NULL || nl-text >= offset)
1060 break;
1061 offset -= (int)(nl+1-text);
1062 text = nl+1;
1063 }
1064 while (*text == ' ' || *text == '\t') {
1065 text++;
1066 offset--;
1067 }
1068 }
1069 PyFile_WriteString(" ", f);
1070 PyFile_WriteString(text, f);
1071 if (*text == '\0' || text[strlen(text)-1] != '\n')
1072 PyFile_WriteString("\n", f);
1073 if (offset == -1)
1074 return;
1075 PyFile_WriteString(" ", f);
1076 offset--;
1077 while (offset > 0) {
1078 PyFile_WriteString(" ", f);
1079 offset--;
1080 }
1081 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001082}
1083
Guido van Rossum66e8e862001-03-23 17:54:43 +00001084static void
1085handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001086{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001087 PyObject *exception, *value, *tb;
1088 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001089
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001090 if (Py_InspectFlag)
1091 /* Don't exit if -i flag was given. This flag is set to 0
1092 * when entering interactive mode for inspecting. */
1093 return;
Georg Brandl49aafc92007-03-07 00:34:46 +00001094
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001095 PyErr_Fetch(&exception, &value, &tb);
1096 if (Py_FlushLine())
1097 PyErr_Clear();
1098 fflush(stdout);
1099 if (value == NULL || value == Py_None)
1100 goto done;
1101 if (PyExceptionInstance_Check(value)) {
1102 /* The error code should be in the `code' attribute. */
1103 PyObject *code = PyObject_GetAttrString(value, "code");
1104 if (code) {
1105 Py_DECREF(value);
1106 value = code;
1107 if (value == Py_None)
1108 goto done;
1109 }
1110 /* If we failed to dig out the 'code' attribute,
1111 just let the else clause below print the error. */
1112 }
1113 if (PyInt_Check(value))
1114 exitcode = (int)PyInt_AsLong(value);
1115 else {
Victor Stinnerc49dfcc2010-05-25 22:30:32 +00001116 PyObject *sys_stderr = PySys_GetObject("stderr");
1117 if (sys_stderr != NULL && sys_stderr != Py_None) {
1118 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1119 } else {
1120 PyObject_Print(value, stderr, Py_PRINT_RAW);
1121 fflush(stderr);
1122 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001123 PySys_WriteStderr("\n");
1124 exitcode = 1;
1125 }
Tim Peterscf615b52003-04-19 18:47:02 +00001126 done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001127 /* Restore and clear the exception info, in order to properly decref
1128 * the exception, value, and traceback. If we just exit instead,
1129 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1130 * some finalizers from running.
1131 */
1132 PyErr_Restore(exception, value, tb);
1133 PyErr_Clear();
1134 Py_Exit(exitcode);
1135 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001136}
1137
1138void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001139PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001140{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001141 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001142
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001143 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1144 handle_system_exit();
1145 }
1146 PyErr_Fetch(&exception, &v, &tb);
1147 if (exception == NULL)
1148 return;
1149 PyErr_NormalizeException(&exception, &v, &tb);
1150 if (exception == NULL)
1151 return;
1152 /* Now we know v != NULL too */
1153 if (set_sys_last_vars) {
1154 PySys_SetObject("last_type", exception);
1155 PySys_SetObject("last_value", v);
1156 PySys_SetObject("last_traceback", tb);
1157 }
1158 hook = PySys_GetObject("excepthook");
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001159 if (hook && hook != Py_None) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001160 PyObject *args = PyTuple_Pack(3,
1161 exception, v, tb ? tb : Py_None);
1162 PyObject *result = PyEval_CallObject(hook, args);
1163 if (result == NULL) {
1164 PyObject *exception2, *v2, *tb2;
1165 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1166 handle_system_exit();
1167 }
1168 PyErr_Fetch(&exception2, &v2, &tb2);
1169 PyErr_NormalizeException(&exception2, &v2, &tb2);
1170 /* It should not be possible for exception2 or v2
1171 to be NULL. However PyErr_Display() can't
1172 tolerate NULLs, so just be safe. */
1173 if (exception2 == NULL) {
1174 exception2 = Py_None;
1175 Py_INCREF(exception2);
1176 }
1177 if (v2 == NULL) {
1178 v2 = Py_None;
1179 Py_INCREF(v2);
1180 }
1181 if (Py_FlushLine())
1182 PyErr_Clear();
1183 fflush(stdout);
1184 PySys_WriteStderr("Error in sys.excepthook:\n");
1185 PyErr_Display(exception2, v2, tb2);
1186 PySys_WriteStderr("\nOriginal exception was:\n");
1187 PyErr_Display(exception, v, tb);
1188 Py_DECREF(exception2);
1189 Py_DECREF(v2);
1190 Py_XDECREF(tb2);
1191 }
1192 Py_XDECREF(result);
1193 Py_XDECREF(args);
1194 } else {
1195 PySys_WriteStderr("sys.excepthook is missing\n");
1196 PyErr_Display(exception, v, tb);
1197 }
1198 Py_XDECREF(exception);
1199 Py_XDECREF(v);
1200 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001201}
1202
Richard Jones7b9558d2006-05-27 12:29:24 +00001203void
1204PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001205{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001206 int err = 0;
1207 PyObject *f = PySys_GetObject("stderr");
1208 Py_INCREF(value);
Antoine Pitroua03ff6d2010-08-08 21:37:51 +00001209 if (f == NULL || f == Py_None)
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001210 fprintf(stderr, "lost sys.stderr\n");
1211 else {
1212 if (Py_FlushLine())
1213 PyErr_Clear();
1214 fflush(stdout);
1215 if (tb && tb != Py_None)
1216 err = PyTraceBack_Print(tb, f);
1217 if (err == 0 &&
1218 PyObject_HasAttrString(value, "print_file_and_line"))
1219 {
1220 PyObject *message;
1221 const char *filename, *text;
1222 int lineno, offset;
1223 if (!parse_syntax_error(value, &message, &filename,
1224 &lineno, &offset, &text))
1225 PyErr_Clear();
1226 else {
1227 char buf[10];
1228 PyFile_WriteString(" File \"", f);
1229 if (filename == NULL)
1230 PyFile_WriteString("<string>", f);
1231 else
1232 PyFile_WriteString(filename, f);
1233 PyFile_WriteString("\", line ", f);
1234 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1235 PyFile_WriteString(buf, f);
1236 PyFile_WriteString("\n", f);
1237 if (text != NULL)
1238 print_error_text(f, offset, text);
1239 Py_DECREF(value);
1240 value = message;
1241 /* Can't be bothered to check all those
1242 PyFile_WriteString() calls */
1243 if (PyErr_Occurred())
1244 err = -1;
1245 }
1246 }
1247 if (err) {
1248 /* Don't do anything else */
1249 }
1250 else if (PyExceptionClass_Check(exception)) {
1251 PyObject* moduleName;
1252 char* className = PyExceptionClass_Name(exception);
1253 if (className != NULL) {
1254 char *dot = strrchr(className, '.');
1255 if (dot != NULL)
1256 className = dot+1;
1257 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001258
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001259 moduleName = PyObject_GetAttrString(exception, "__module__");
1260 if (moduleName == NULL)
1261 err = PyFile_WriteString("<unknown>", f);
1262 else {
1263 char* modstr = PyString_AsString(moduleName);
1264 if (modstr && strcmp(modstr, "exceptions"))
1265 {
1266 err = PyFile_WriteString(modstr, f);
1267 err += PyFile_WriteString(".", f);
1268 }
1269 Py_DECREF(moduleName);
1270 }
1271 if (err == 0) {
1272 if (className == NULL)
1273 err = PyFile_WriteString("<unknown>", f);
1274 else
1275 err = PyFile_WriteString(className, f);
1276 }
1277 }
1278 else
1279 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1280 if (err == 0 && (value != Py_None)) {
1281 PyObject *s = PyObject_Str(value);
1282 /* only print colon if the str() of the
1283 object is not the empty string
1284 */
1285 if (s == NULL)
1286 err = -1;
1287 else if (!PyString_Check(s) ||
1288 PyString_GET_SIZE(s) != 0)
1289 err = PyFile_WriteString(": ", f);
1290 if (err == 0)
1291 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1292 Py_XDECREF(s);
1293 }
1294 /* try to write a newline in any case */
1295 err += PyFile_WriteString("\n", f);
1296 }
1297 Py_DECREF(value);
1298 /* If an error happened here, don't show it.
1299 XXX This is wrong, but too many callers rely on this behavior. */
1300 if (err != 0)
1301 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001302}
1303
Guido van Rossum82598051997-03-05 00:20:32 +00001304PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001305PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001306 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001307{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001308 PyObject *ret = NULL;
1309 mod_ty mod;
1310 PyArena *arena = PyArena_New();
1311 if (arena == NULL)
1312 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001313
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001314 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1315 if (mod != NULL)
1316 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1317 PyArena_Free(arena);
1318 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001319}
1320
1321PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001322PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001323 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001324{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001325 PyObject *ret;
1326 mod_ty mod;
1327 PyArena *arena = PyArena_New();
1328 if (arena == NULL)
1329 return NULL;
Brett Cannonc33e82d2010-05-05 20:38:52 +00001330
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001331 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1332 flags, NULL, arena);
1333 if (closeit)
1334 fclose(fp);
1335 if (mod == NULL) {
1336 PyArena_Free(arena);
1337 return NULL;
1338 }
1339 ret = run_mod(mod, filename, globals, locals, flags, arena);
1340 PyArena_Free(arena);
1341 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001342}
1343
Guido van Rossum82598051997-03-05 00:20:32 +00001344static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001345run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001346 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001347{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001348 PyCodeObject *co;
1349 PyObject *v;
1350 co = PyAST_Compile(mod, filename, flags, arena);
1351 if (co == NULL)
1352 return NULL;
1353 v = PyEval_EvalCode(co, globals, locals);
1354 Py_DECREF(co);
1355 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001356}
1357
Guido van Rossum82598051997-03-05 00:20:32 +00001358static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001359run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001360 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001361{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001362 PyCodeObject *co;
1363 PyObject *v;
1364 long magic;
1365 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001366
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001367 magic = PyMarshal_ReadLongFromFile(fp);
1368 if (magic != PyImport_GetMagicNumber()) {
1369 PyErr_SetString(PyExc_RuntimeError,
1370 "Bad magic number in .pyc file");
1371 return NULL;
1372 }
1373 (void) PyMarshal_ReadLongFromFile(fp);
1374 v = PyMarshal_ReadLastObjectFromFile(fp);
1375 fclose(fp);
1376 if (v == NULL || !PyCode_Check(v)) {
1377 Py_XDECREF(v);
1378 PyErr_SetString(PyExc_RuntimeError,
1379 "Bad code object in .pyc file");
1380 return NULL;
1381 }
1382 co = (PyCodeObject *)v;
1383 v = PyEval_EvalCode(co, globals, locals);
1384 if (v && flags)
1385 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1386 Py_DECREF(co);
1387 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001388}
1389
Guido van Rossum82598051997-03-05 00:20:32 +00001390PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001391Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001392 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001393{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001394 PyCodeObject *co;
1395 mod_ty mod;
1396 PyArena *arena = PyArena_New();
1397 if (arena == NULL)
1398 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001399
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001400 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1401 if (mod == NULL) {
1402 PyArena_Free(arena);
1403 return NULL;
1404 }
1405 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1406 PyObject *result = PyAST_mod2obj(mod);
1407 PyArena_Free(arena);
1408 return result;
1409 }
1410 co = PyAST_Compile(mod, filename, flags, arena);
1411 PyArena_Free(arena);
1412 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001413}
1414
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001415struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001416Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001417{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001418 struct symtable *st;
1419 mod_ty mod;
1420 PyCompilerFlags flags;
1421 PyArena *arena = PyArena_New();
1422 if (arena == NULL)
1423 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001424
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001425 flags.cf_flags = 0;
Christian Heimes7f23d862008-03-26 22:51:58 +00001426
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001427 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1428 if (mod == NULL) {
1429 PyArena_Free(arena);
1430 return NULL;
1431 }
1432 st = PySymtable_Build(mod, filename, 0);
1433 PyArena_Free(arena);
1434 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001435}
1436
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001437/* Preferred access to parser is through AST. */
1438mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001439PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001440 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001442 mod_ty mod;
1443 PyCompilerFlags localflags;
1444 perrdetail err;
1445 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001446
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001447 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1448 &_PyParser_Grammar, start, &err,
1449 &iflags);
1450 if (flags == NULL) {
1451 localflags.cf_flags = 0;
1452 flags = &localflags;
1453 }
1454 if (n) {
1455 flags->cf_flags |= iflags & PyCF_MASK;
1456 mod = PyAST_FromNode(n, flags, filename, arena);
1457 PyNode_Free(n);
1458 return mod;
1459 }
1460 else {
1461 err_input(&err);
1462 return NULL;
1463 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001464}
1465
1466mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001467PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001468 char *ps2, PyCompilerFlags *flags, int *errcode,
1469 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001470{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001471 mod_ty mod;
1472 PyCompilerFlags localflags;
1473 perrdetail err;
1474 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001475
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001476 node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
1477 start, ps1, ps2, &err, &iflags);
1478 if (flags == NULL) {
1479 localflags.cf_flags = 0;
1480 flags = &localflags;
1481 }
1482 if (n) {
1483 flags->cf_flags |= iflags & PyCF_MASK;
1484 mod = PyAST_FromNode(n, flags, filename, arena);
1485 PyNode_Free(n);
1486 return mod;
1487 }
1488 else {
1489 err_input(&err);
1490 if (errcode)
1491 *errcode = err.error;
1492 return NULL;
1493 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001494}
1495
Guido van Rossuma110aa61994-08-29 12:50:44 +00001496/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001497
Guido van Rossuma110aa61994-08-29 12:50:44 +00001498node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001499PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001500{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001501 perrdetail err;
1502 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1503 start, NULL, NULL, &err, flags);
1504 if (n == NULL)
1505 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001506
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001507 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001508}
1509
Guido van Rossuma110aa61994-08-29 12:50:44 +00001510/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001511
Guido van Rossuma110aa61994-08-29 12:50:44 +00001512node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001513PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001514{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001515 perrdetail err;
1516 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1517 start, &err, flags);
1518 if (n == NULL)
1519 err_input(&err);
1520 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001521}
1522
1523node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001524PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001525 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001526{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001527 perrdetail err;
1528 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1529 &_PyParser_Grammar, start, &err, flags);
1530 if (n == NULL)
1531 err_input(&err);
1532 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001533}
1534
1535node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001536PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001537{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001538 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001539}
1540
Guido van Rossum66ebd912003-04-17 16:02:26 +00001541/* May want to move a more generalized form of this to parsetok.c or
1542 even parser modules. */
1543
1544void
1545PyParser_SetError(perrdetail *err)
1546{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001547 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001548}
1549
Guido van Rossuma110aa61994-08-29 12:50:44 +00001550/* Set the error appropriate to the given input error code (see errcode.h) */
1551
1552static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001553err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001554{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001555 PyObject *v, *w, *errtype;
1556 PyObject* u = NULL;
1557 char *msg = NULL;
1558 errtype = PyExc_SyntaxError;
1559 switch (err->error) {
1560 case E_ERROR:
1561 return;
1562 case E_SYNTAX:
1563 errtype = PyExc_IndentationError;
1564 if (err->expected == INDENT)
1565 msg = "expected an indented block";
1566 else if (err->token == INDENT)
1567 msg = "unexpected indent";
1568 else if (err->token == DEDENT)
1569 msg = "unexpected unindent";
1570 else {
1571 errtype = PyExc_SyntaxError;
1572 msg = "invalid syntax";
1573 }
1574 break;
1575 case E_TOKEN:
1576 msg = "invalid token";
1577 break;
1578 case E_EOFS:
1579 msg = "EOF while scanning triple-quoted string literal";
1580 break;
1581 case E_EOLS:
1582 msg = "EOL while scanning string literal";
1583 break;
1584 case E_INTR:
1585 if (!PyErr_Occurred())
1586 PyErr_SetNone(PyExc_KeyboardInterrupt);
1587 goto cleanup;
1588 case E_NOMEM:
1589 PyErr_NoMemory();
1590 goto cleanup;
1591 case E_EOF:
1592 msg = "unexpected EOF while parsing";
1593 break;
1594 case E_TABSPACE:
1595 errtype = PyExc_TabError;
1596 msg = "inconsistent use of tabs and spaces in indentation";
1597 break;
1598 case E_OVERFLOW:
1599 msg = "expression too long";
1600 break;
1601 case E_DEDENT:
1602 errtype = PyExc_IndentationError;
1603 msg = "unindent does not match any outer indentation level";
1604 break;
1605 case E_TOODEEP:
1606 errtype = PyExc_IndentationError;
1607 msg = "too many levels of indentation";
1608 break;
1609 case E_DECODE: {
1610 PyObject *type, *value, *tb;
1611 PyErr_Fetch(&type, &value, &tb);
1612 if (value != NULL) {
1613 u = PyObject_Str(value);
1614 if (u != NULL) {
1615 msg = PyString_AsString(u);
1616 }
1617 }
1618 if (msg == NULL)
1619 msg = "unknown decode error";
1620 Py_XDECREF(type);
1621 Py_XDECREF(value);
1622 Py_XDECREF(tb);
1623 break;
1624 }
1625 case E_LINECONT:
1626 msg = "unexpected character after line continuation character";
1627 break;
1628 default:
1629 fprintf(stderr, "error=%d\n", err->error);
1630 msg = "unknown parsing error";
1631 break;
1632 }
1633 v = Py_BuildValue("(ziiz)", err->filename,
1634 err->lineno, err->offset, err->text);
1635 w = NULL;
1636 if (v != NULL)
1637 w = Py_BuildValue("(sO)", msg, v);
1638 Py_XDECREF(u);
1639 Py_XDECREF(v);
1640 PyErr_SetObject(errtype, w);
1641 Py_XDECREF(w);
Georg Brandl1ad108d2008-07-19 10:08:55 +00001642cleanup:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001643 if (err->text != NULL) {
1644 PyObject_FREE(err->text);
1645 err->text = NULL;
1646 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001647}
1648
1649/* Print fatal error message and abort */
1650
1651void
Tim Peters7c321a82002-07-09 02:57:01 +00001652Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001653{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001654 fprintf(stderr, "Fatal Python error: %s\n", msg);
1655 fflush(stderr); /* it helps in Windows debug build */
Jesse Noller42f9b4e2009-03-31 22:20:35 +00001656
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001657#ifdef MS_WINDOWS
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001658 {
1659 size_t len = strlen(msg);
1660 WCHAR* buffer;
1661 size_t i;
Martin v. Löwis5344c992009-01-02 20:32:55 +00001662
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001663 /* Convert the message to wchar_t. This uses a simple one-to-one
1664 conversion, assuming that the this error message actually uses ASCII
1665 only. If this ceases to be true, we will have to convert. */
1666 buffer = alloca( (len+1) * (sizeof *buffer));
1667 for( i=0; i<=len; ++i)
1668 buffer[i] = msg[i];
1669 OutputDebugStringW(L"Fatal Python error: ");
1670 OutputDebugStringW(buffer);
1671 OutputDebugStringW(L"\n");
1672 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001673#ifdef _DEBUG
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001674 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001675#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001676#endif /* MS_WINDOWS */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001677 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001678}
1679
1680/* Clean up and exit */
1681
Guido van Rossuma110aa61994-08-29 12:50:44 +00001682#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001683#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001684#endif
1685
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001686/* Wait until threading._shutdown completes, provided
1687 the threading module was imported in the first place.
1688 The shutdown routine will wait until all non-daemon
1689 "threading" threads have completed. */
1690static void
1691wait_for_thread_shutdown(void)
1692{
1693#ifdef WITH_THREAD
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001694 PyObject *result;
1695 PyThreadState *tstate = PyThreadState_GET();
1696 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1697 "threading");
1698 if (threading == NULL) {
1699 /* threading not imported */
1700 PyErr_Clear();
1701 return;
1702 }
1703 result = PyObject_CallMethod(threading, "_shutdown", "");
1704 if (result == NULL)
1705 PyErr_WriteUnraisable(threading);
1706 else
1707 Py_DECREF(result);
1708 Py_DECREF(threading);
Antoine Pitrouefb60c02009-10-20 21:29:37 +00001709#endif
1710}
1711
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001712#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001713static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001714static int nexitfuncs = 0;
1715
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001716int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001717{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001718 if (nexitfuncs >= NEXITFUNCS)
1719 return -1;
1720 exitfuncs[nexitfuncs++] = func;
1721 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00001722}
1723
Guido van Rossumcc283f51997-08-05 02:22:03 +00001724static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001725call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001726{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001727 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001728
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001729 if (exitfunc) {
1730 PyObject *res;
1731 Py_INCREF(exitfunc);
1732 PySys_SetObject("exitfunc", (PyObject *)NULL);
1733 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1734 if (res == NULL) {
1735 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1736 PySys_WriteStderr("Error in sys.exitfunc:\n");
1737 }
1738 PyErr_Print();
1739 }
1740 Py_DECREF(exitfunc);
1741 }
Guido van Rossum59bff391992-09-03 20:28:00 +00001742
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001743 if (Py_FlushLine())
1744 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001745}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001746
Guido van Rossumcc283f51997-08-05 02:22:03 +00001747static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001748call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001749{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001750 while (nexitfuncs > 0)
1751 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001752
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001753 fflush(stdout);
1754 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001755}
1756
1757void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001758Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001759{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001760 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001761
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001762 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001763}
1764
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001765static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001766initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001767{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001768#ifdef SIGPIPE
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001769 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001770#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001771#ifdef SIGXFZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001772 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001773#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001774#ifdef SIGXFSZ
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001775 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001776#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001777 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001778}
1779
Guido van Rossum7433b121997-02-14 19:45:36 +00001780
1781/*
1782 * The file descriptor fd is considered ``interactive'' if either
1783 * a) isatty(fd) is TRUE, or
1784 * b) the -i flag was given, and the filename associated with
1785 * the descriptor is NULL or "<stdin>" or "???".
1786 */
1787int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001788Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001789{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001790 if (isatty((int)fileno(fp)))
1791 return 1;
1792 if (!Py_InteractiveFlag)
1793 return 0;
1794 return (filename == NULL) ||
1795 (strcmp(filename, "<stdin>") == 0) ||
1796 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00001797}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001798
1799
Tim Petersd08e3822003-04-17 15:24:21 +00001800#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001801#if defined(WIN32) && defined(_MSC_VER)
1802
1803/* Stack checking for Microsoft C */
1804
1805#include <malloc.h>
1806#include <excpt.h>
1807
Fred Drakee8de31c2000-08-31 05:38:39 +00001808/*
1809 * Return non-zero when we run out of memory on the stack; zero otherwise.
1810 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001811int
Fred Drake399739f2000-08-31 05:52:44 +00001812PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001813{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001814 __try {
1815 /* alloca throws a stack overflow exception if there's
1816 not enough space left on the stack */
1817 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1818 return 0;
1819 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1820 EXCEPTION_EXECUTE_HANDLER :
1821 EXCEPTION_CONTINUE_SEARCH) {
1822 int errcode = _resetstkoflw();
1823 if (errcode == 0)
1824 {
1825 Py_FatalError("Could not reset the stack!");
1826 }
1827 }
1828 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001829}
1830
1831#endif /* WIN32 && _MSC_VER */
1832
1833/* Alternate implementations can be added here... */
1834
1835#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001836
1837
1838/* Wrappers around sigaction() or signal(). */
1839
1840PyOS_sighandler_t
1841PyOS_getsig(int sig)
1842{
1843#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001844 struct sigaction context;
1845 if (sigaction(sig, NULL, &context) == -1)
1846 return SIG_ERR;
1847 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001848#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001849 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001850/* Special signal handling for the secure CRT in Visual Studio 2005 */
1851#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001852 switch (sig) {
1853 /* Only these signals are valid */
1854 case SIGINT:
1855 case SIGILL:
1856 case SIGFPE:
1857 case SIGSEGV:
1858 case SIGTERM:
1859 case SIGBREAK:
1860 case SIGABRT:
1861 break;
1862 /* Don't call signal() with other values or it will assert */
1863 default:
1864 return SIG_ERR;
1865 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001866#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001867 handler = signal(sig, SIG_IGN);
1868 if (handler != SIG_ERR)
1869 signal(sig, handler);
1870 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001871#endif
1872}
1873
1874PyOS_sighandler_t
1875PyOS_setsig(int sig, PyOS_sighandler_t handler)
1876{
1877#ifdef HAVE_SIGACTION
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001878 /* Some code in Modules/signalmodule.c depends on sigaction() being
1879 * used here if HAVE_SIGACTION is defined. Fix that if this code
1880 * changes to invalidate that assumption.
1881 */
1882 struct sigaction context, ocontext;
1883 context.sa_handler = handler;
1884 sigemptyset(&context.sa_mask);
1885 context.sa_flags = 0;
1886 if (sigaction(sig, &context, &ocontext) == -1)
1887 return SIG_ERR;
1888 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001889#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001890 PyOS_sighandler_t oldhandler;
1891 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001892#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001893 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001894#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001895 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001896#endif
1897}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001898
1899/* Deprecated C API functions still provided for binary compatiblity */
1900
1901#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001902PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1904{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001905 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001906}
1907
Thomas Heller1b046642006-04-18 18:51:06 +00001908#undef PyParser_SimpleParseString
1909PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910PyParser_SimpleParseString(const char *str, int start)
1911{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001912 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001913}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001914
Thomas Heller1b046642006-04-18 18:51:06 +00001915#undef PyRun_AnyFile
1916PyAPI_FUNC(int)
1917PyRun_AnyFile(FILE *fp, const char *name)
1918{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001919 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001920}
1921
1922#undef PyRun_AnyFileEx
1923PyAPI_FUNC(int)
1924PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1925{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001926 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001927}
1928
1929#undef PyRun_AnyFileFlags
1930PyAPI_FUNC(int)
1931PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1932{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001933 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001934}
1935
1936#undef PyRun_File
1937PyAPI_FUNC(PyObject *)
1938PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1939{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001940 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001941}
1942
1943#undef PyRun_FileEx
1944PyAPI_FUNC(PyObject *)
1945PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1946{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001947 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001948}
1949
1950#undef PyRun_FileFlags
1951PyAPI_FUNC(PyObject *)
1952PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001953 PyCompilerFlags *flags)
Thomas Heller1b046642006-04-18 18:51:06 +00001954{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001955 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001956}
1957
1958#undef PyRun_SimpleFile
1959PyAPI_FUNC(int)
1960PyRun_SimpleFile(FILE *f, const char *p)
1961{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001962 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001963}
1964
1965#undef PyRun_SimpleFileEx
1966PyAPI_FUNC(int)
1967PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1968{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001969 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001970}
1971
1972
1973#undef PyRun_String
1974PyAPI_FUNC(PyObject *)
1975PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1976{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001977 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001978}
1979
1980#undef PyRun_SimpleString
1981PyAPI_FUNC(int)
1982PyRun_SimpleString(const char *s)
1983{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001984 return PyRun_SimpleStringFlags(s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001985}
1986
1987#undef Py_CompileString
1988PyAPI_FUNC(PyObject *)
1989Py_CompileString(const char *str, const char *p, int s)
1990{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001991 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001992}
1993
1994#undef PyRun_InteractiveOne
1995PyAPI_FUNC(int)
1996PyRun_InteractiveOne(FILE *f, const char *p)
1997{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001998 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001999}
2000
2001#undef PyRun_InteractiveLoop
2002PyAPI_FUNC(int)
2003PyRun_InteractiveLoop(FILE *f, const char *p)
2004{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002005 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002006}
2007
Anthony Baxterac6bd462006-04-13 02:06:09 +00002008#ifdef __cplusplus
2009}
2010#endif
2011