blob: 2f8318bc5fe0f4e42eb13f736d0287daf989e4a4 [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 Pitrou9aece752009-10-27 12:48:52 +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
Georg Brandl734373c2009-01-03 21:55:17 +000026#ifdef MS_WINDOWS
27#include "malloc.h" /* for alloca */
28#endif
29
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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +000060 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000061static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +000062 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000063static void err_input(perrdetail *);
64static void initsigs(void);
Antoine Pitrou9aece752009-10-27 12:48:52 +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 Brandl49aafc92007-03-07 00:34:46 +000079int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +0000153 char ibuf[128];
154 char buf[128];
Martin v. Löwis99815892008-06-01 07:20:46 +0000155#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000156 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000157
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000158 if (initialized)
159 return;
160 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000161
Antoine Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +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 Pitrouc7c96a92010-05-09 15:15:40 +0000186 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000187
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000188 if (!_PyFrame_Init())
189 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000190
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000191 if (!_PyInt_Init())
192 Py_FatalError("Py_Initialize: can't init ints");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000193
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000194 if (!PyByteArray_Init())
195 Py_FatalError("Py_Initialize: can't init bytearray");
Christian Heimes1a6387e2008-03-26 12:49:49 +0000196
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000197 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000198
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000199 interp->modules = PyDict_New();
200 if (interp->modules == NULL)
201 Py_FatalError("Py_Initialize: can't make modules dictionary");
202 interp->modules_reloading = PyDict_New();
203 if (interp->modules_reloading == NULL)
204 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000205
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000206#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000207 /* Init Unicode implementation; relies on the codec registry */
208 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000209#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000210
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000211 bimod = _PyBuiltin_Init();
212 if (bimod == NULL)
213 Py_FatalError("Py_Initialize: can't initialize __builtin__");
214 interp->builtins = PyModule_GetDict(bimod);
215 if (interp->builtins == NULL)
216 Py_FatalError("Py_Initialize: can't initialize builtins dict");
217 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000218
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000219 sysmod = _PySys_Init();
220 if (sysmod == NULL)
221 Py_FatalError("Py_Initialize: can't initialize sys");
222 interp->sysdict = PyModule_GetDict(sysmod);
223 if (interp->sysdict == NULL)
224 Py_FatalError("Py_Initialize: can't initialize sys dict");
225 Py_INCREF(interp->sysdict);
226 _PyImport_FixupExtension("sys", "sys");
227 PySys_SetPath(Py_GetPath());
228 PyDict_SetItemString(interp->sysdict, "modules",
229 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000230
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000231 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000232
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000233 /* initialize builtin exceptions */
234 _PyExc_Init();
235 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000236
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000237 /* phase 2 of builtins */
238 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000239
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000240 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000241
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000242 if (install_sigs)
243 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000244
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000245 /* Initialize warnings. */
246 _PyWarnings_Init();
247 if (PySys_HasWarnOptions()) {
248 PyObject *warnings_module = PyImport_ImportModule("warnings");
249 if (!warnings_module)
250 PyErr_Clear();
251 Py_XDECREF(warnings_module);
252 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000253
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000254 initmain(); /* Module __main__ */
255
256 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000257#ifdef WITH_THREAD
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000258 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000259#endif /* WITH_THREAD */
260
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000261 if (!Py_NoSiteFlag)
262 initsite(); /* Module site */
Victor Stinnerea164292010-03-21 14:02:32 +0000263
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000264 if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
265 p = icodeset = codeset = strdup(p);
266 free_codeset = 1;
267 errors = strchr(p, ':');
268 if (errors) {
269 *errors = '\0';
270 errors++;
271 }
272 overridden = 1;
273 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000274
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000275#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000276 /* On Unix, set the file system encoding according to the
277 user's preference, if the CODESET names a well-known
278 Python codec, and Py_FileSystemDefaultEncoding isn't
279 initialized by other means. Also set the encoding of
280 stdin and stdout if these are terminals, unless overridden. */
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000281
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000282 if (!overridden || !Py_FileSystemDefaultEncoding) {
283 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
284 setlocale(LC_CTYPE, "");
285 loc_codeset = nl_langinfo(CODESET);
286 if (loc_codeset && *loc_codeset) {
287 PyObject *enc = PyCodec_Encoder(loc_codeset);
288 if (enc) {
289 loc_codeset = strdup(loc_codeset);
290 Py_DECREF(enc);
291 } else {
292 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
293 PyErr_Clear();
294 loc_codeset = NULL;
295 } else {
296 PyErr_Print();
297 exit(1);
298 }
299 }
300 } else
301 loc_codeset = NULL;
302 setlocale(LC_CTYPE, saved_locale);
303 free(saved_locale);
Martin v. Löwis99815892008-06-01 07:20:46 +0000304
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000305 if (!overridden) {
306 codeset = icodeset = loc_codeset;
307 free_codeset = 1;
308 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000309
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000310 /* Initialize Py_FileSystemDefaultEncoding from
311 locale even if PYTHONIOENCODING is set. */
312 if (!Py_FileSystemDefaultEncoding) {
313 Py_FileSystemDefaultEncoding = loc_codeset;
314 if (!overridden)
315 free_codeset = 0;
316 }
317 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000318#endif
319
320#ifdef MS_WINDOWS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000321 if (!overridden) {
322 icodeset = ibuf;
323 codeset = buf;
324 sprintf(ibuf, "cp%d", GetConsoleCP());
325 sprintf(buf, "cp%d", GetConsoleOutputCP());
326 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000327#endif
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000328
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000329 if (codeset) {
330 sys_stream = PySys_GetObject("stdin");
331 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
332 if (!sys_isatty)
333 PyErr_Clear();
334 if ((overridden ||
335 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
336 PyFile_Check(sys_stream)) {
337 if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
338 Py_FatalError("Cannot set codeset of stdin");
339 }
340 Py_XDECREF(sys_isatty);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000341
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000342 sys_stream = PySys_GetObject("stdout");
343 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
344 if (!sys_isatty)
345 PyErr_Clear();
346 if ((overridden ||
347 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
348 PyFile_Check(sys_stream)) {
349 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
350 Py_FatalError("Cannot set codeset of stdout");
351 }
352 Py_XDECREF(sys_isatty);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000353
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000354 sys_stream = PySys_GetObject("stderr");
355 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
356 if (!sys_isatty)
357 PyErr_Clear();
358 if((overridden ||
359 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
360 PyFile_Check(sys_stream)) {
361 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
362 Py_FatalError("Cannot set codeset of stderr");
363 }
364 Py_XDECREF(sys_isatty);
Martin v. Löwisea62d252006-04-03 10:56:49 +0000365
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000366 if (free_codeset)
367 free(codeset);
368 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000369}
370
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000371void
372Py_Initialize(void)
373{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000374 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000375}
376
377
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000378#ifdef COUNT_ALLOCS
Martin v. Löwis45294a92006-04-18 06:24:08 +0000379extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000380#endif
381
Guido van Rossum25ce5661997-08-02 03:10:38 +0000382/* Undo the effect of Py_Initialize().
383
384 Beware: if multiple interpreter and/or thread states exist, these
385 are not wiped out; only the current thread and interpreter state
386 are deleted. But since everything else is deleted, those other
387 interpreter and thread states should no longer be used.
388
389 (XXX We should do better, e.g. wipe out all interpreters and
390 threads.)
391
392 Locking: as above.
393
394*/
395
396void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000397Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000398{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000399 PyInterpreterState *interp;
400 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000401
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000402 if (!initialized)
403 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000404
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000405 wait_for_thread_shutdown();
Antoine Pitrou9aece752009-10-27 12:48:52 +0000406
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000407 /* The interpreter is still entirely intact at this point, and the
408 * exit funcs may be relying on that. In particular, if some thread
409 * or exit func is still waiting to do an import, the import machinery
410 * expects Py_IsInitialized() to return true. So don't say the
411 * interpreter is uninitialized until after the exit funcs have run.
412 * Note that Threading.py uses an exit func to do a join on all the
413 * threads created thru it, so this also protects pending imports in
414 * the threads created via Threading.
415 */
416 call_sys_exitfunc();
417 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000418
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000419 /* Get current thread state and interpreter pointer */
420 tstate = PyThreadState_GET();
421 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000422
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000423 /* Disable signal handling */
424 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000425
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000426 /* Clear type lookup cache */
427 PyType_ClearCache();
Christian Heimes908caac2008-01-27 23:34:59 +0000428
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000429 /* Collect garbage. This may call finalizers; it's nice to call these
430 * before all modules are destroyed.
431 * XXX If a __del__ or weakref callback is triggered here, and tries to
432 * XXX import a module, bad things can happen, because Python no
433 * XXX longer believes it's initialized.
434 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
435 * XXX is easy to provoke that way. I've also seen, e.g.,
436 * XXX Exception exceptions.ImportError: 'No module named sha'
437 * XXX in <function callback at 0x008F5718> ignored
438 * XXX but I'm unclear on exactly how that one happens. In any case,
439 * XXX I haven't seen a real-life report of either of these.
440 */
441 PyGC_Collect();
Martin v. Löwis45294a92006-04-18 06:24:08 +0000442#ifdef COUNT_ALLOCS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000443 /* With COUNT_ALLOCS, it helps to run GC multiple times:
444 each collection might release some types from the type
445 list, so they become garbage. */
446 while (PyGC_Collect() > 0)
447 /* nothing */;
Martin v. Löwis45294a92006-04-18 06:24:08 +0000448#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000449
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000450 /* Destroy all modules */
451 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000452
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000453 /* Collect final garbage. This disposes of cycles created by
454 * new-style class definitions, for example.
455 * XXX This is disabled because it caused too many problems. If
456 * XXX a __del__ or weakref callback triggers here, Python code has
457 * XXX a hard time running, because even the sys module has been
458 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
459 * XXX One symptom is a sequence of information-free messages
460 * XXX coming from threads (if a __del__ or callback is invoked,
461 * XXX other threads can execute too, and any exception they encounter
462 * XXX triggers a comedy of errors as subsystem after subsystem
463 * XXX fails to find what it *expects* to find in sys to help report
464 * XXX the exception and consequent unexpected failures). I've also
465 * XXX seen segfaults then, after adding print statements to the
466 * XXX Python code getting called.
467 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000468#if 0
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000469 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000470#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000471
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000472 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
473 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000474
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000475 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000476#ifdef COUNT_ALLOCS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000477 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000478#endif
479
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000480 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000481
Tim Peters9cf25ce2003-04-17 15:21:01 +0000482#ifdef Py_TRACE_REFS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000483 /* Display all objects still alive -- this can invoke arbitrary
484 * __repr__ overrides, so requires a mostly-intact interpreter.
485 * Alas, a lot of stuff may still be alive now that will be cleaned
486 * up later.
487 */
488 if (Py_GETENV("PYTHONDUMPREFS"))
489 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000490#endif /* Py_TRACE_REFS */
491
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000492 /* Clear interpreter state */
493 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000494
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000495 /* Now we decref the exception classes. After this point nothing
496 can raise an exception. That's okay, because each Fini() method
497 below has been checked to make sure no exceptions are ever
498 raised.
499 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000500
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000501 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000502
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000503 /* Cleanup auto-thread-state */
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000504#ifdef WITH_THREAD
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000505 _PyGILState_Fini();
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000506#endif /* WITH_THREAD */
507
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000508 /* Delete current thread */
509 PyThreadState_Swap(NULL);
510 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000511
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000512 /* Sundry finalizers */
513 PyMethod_Fini();
514 PyFrame_Fini();
515 PyCFunction_Fini();
516 PyTuple_Fini();
517 PyList_Fini();
518 PySet_Fini();
519 PyString_Fini();
520 PyByteArray_Fini();
521 PyInt_Fini();
522 PyFloat_Fini();
523 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000524
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000525#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000526 /* Cleanup Unicode implementation */
527 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000528#endif
529
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000530 /* XXX Still allocated:
531 - various static ad-hoc pointers to interned strings
532 - int and float free list blocks
533 - whatever various modules and libraries allocate
534 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000535
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000536 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000537
Tim Peters269b2a62003-04-17 19:52:29 +0000538#ifdef Py_TRACE_REFS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000539 /* Display addresses (& refcnts) of all objects still alive.
540 * An address can be used to find the repr of the object, printed
541 * above by _Py_PrintReferences.
542 */
543 if (Py_GETENV("PYTHONDUMPREFS"))
544 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000545#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000546#ifdef PYMALLOC_DEBUG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000547 if (Py_GETENV("PYTHONMALLOCSTATS"))
548 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000549#endif
550
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000551 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000552}
553
554/* Create and initialize a new interpreter and thread, and return the
555 new thread. This requires that Py_Initialize() has been called
556 first.
557
558 Unsuccessful initialization yields a NULL pointer. Note that *no*
559 exception information is available even in this case -- the
560 exception information is held in the thread, and there is no
561 thread.
562
563 Locking: as above.
564
565*/
566
567PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000568Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000570 PyInterpreterState *interp;
571 PyThreadState *tstate, *save_tstate;
572 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000574 if (!initialized)
575 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000577 interp = PyInterpreterState_New();
578 if (interp == NULL)
579 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000580
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000581 tstate = PyThreadState_New(interp);
582 if (tstate == NULL) {
583 PyInterpreterState_Delete(interp);
584 return NULL;
585 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000586
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000587 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000589 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000591 interp->modules = PyDict_New();
592 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000593
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000594 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
595 if (bimod != NULL) {
596 interp->builtins = PyModule_GetDict(bimod);
597 if (interp->builtins == NULL)
598 goto handle_error;
599 Py_INCREF(interp->builtins);
600 }
601 sysmod = _PyImport_FindExtension("sys", "sys");
602 if (bimod != NULL && sysmod != NULL) {
603 interp->sysdict = PyModule_GetDict(sysmod);
604 if (interp->sysdict == NULL)
605 goto handle_error;
606 Py_INCREF(interp->sysdict);
607 PySys_SetPath(Py_GetPath());
608 PyDict_SetItemString(interp->sysdict, "modules",
609 interp->modules);
610 _PyImportHooks_Init();
611 initmain();
612 if (!Py_NoSiteFlag)
613 initsite();
614 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000615
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000616 if (!PyErr_Occurred())
617 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000618
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000619handle_error:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000620 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000622 PyErr_Print();
623 PyThreadState_Clear(tstate);
624 PyThreadState_Swap(save_tstate);
625 PyThreadState_Delete(tstate);
626 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000627
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000628 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629}
630
631/* Delete an interpreter and its last thread. This requires that the
632 given thread state is current, that the thread has no remaining
633 frames, and that it is its interpreter's only remaining thread.
634 It is a fatal error to violate these constraints.
635
636 (Py_Finalize() doesn't have these constraints -- it zaps
637 everything, regardless.)
638
639 Locking: as above.
640
641*/
642
643void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000644Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000645{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000646 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000647
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000648 if (tstate != PyThreadState_GET())
649 Py_FatalError("Py_EndInterpreter: thread is not current");
650 if (tstate->frame != NULL)
651 Py_FatalError("Py_EndInterpreter: thread still has a frame");
652 if (tstate != interp->tstate_head || tstate->next != NULL)
653 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000654
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000655 PyImport_Cleanup();
656 PyInterpreterState_Clear(interp);
657 PyThreadState_Swap(NULL);
658 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000659}
660
661static char *progname = "python";
662
663void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000664Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000665{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000666 if (pn && *pn)
667 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000668}
669
670char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000671Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000672{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000673 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000674}
675
Guido van Rossuma61691e1998-02-06 22:27:24 +0000676static char *default_home = NULL;
677
678void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000679Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000680{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000681 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000682}
683
684char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000685Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000686{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000687 char *home = default_home;
688 if (home == NULL && !Py_IgnoreEnvironmentFlag)
689 home = Py_GETENV("PYTHONHOME");
690 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000691}
692
Guido van Rossum6135a871995-01-09 17:53:26 +0000693/* Create __main__ module */
694
695static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000696initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000697{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000698 PyObject *m, *d;
699 m = PyImport_AddModule("__main__");
700 if (m == NULL)
701 Py_FatalError("can't create __main__ module");
702 d = PyModule_GetDict(m);
703 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
704 PyObject *bimod = PyImport_ImportModule("__builtin__");
705 if (bimod == NULL ||
706 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
707 Py_FatalError("can't add __builtins__ to __main__");
708 Py_DECREF(bimod);
709 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000710}
711
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000712/* Import the site module (not into __main__ though) */
713
714static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000715initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000716{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000717 PyObject *m, *f;
718 m = PyImport_ImportModule("site");
719 if (m == NULL) {
720 f = PySys_GetObject("stderr");
721 if (Py_VerboseFlag) {
722 PyFile_WriteString(
723 "'import site' failed; traceback:\n", f);
724 PyErr_Print();
725 }
726 else {
727 PyFile_WriteString(
728 "'import site' failed; use -v for traceback\n", f);
729 PyErr_Clear();
730 }
731 }
732 else {
733 Py_DECREF(m);
734 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000735}
736
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000737/* Parse input from a file and execute it */
738
739int
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000740PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000741 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000742{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000743 if (filename == NULL)
744 filename = "???";
745 if (Py_FdIsInteractive(fp, filename)) {
746 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
747 if (closeit)
748 fclose(fp);
749 return err;
750 }
751 else
752 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000753}
754
755int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000756PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000757{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000758 PyObject *v;
759 int ret;
760 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000761
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000762 if (flags == NULL) {
763 flags = &local_flags;
764 local_flags.cf_flags = 0;
765 }
766 v = PySys_GetObject("ps1");
767 if (v == NULL) {
768 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
769 Py_XDECREF(v);
770 }
771 v = PySys_GetObject("ps2");
772 if (v == NULL) {
773 PySys_SetObject("ps2", v = PyString_FromString("... "));
774 Py_XDECREF(v);
775 }
776 for (;;) {
777 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
778 PRINT_TOTAL_REFS();
779 if (ret == E_EOF)
780 return 0;
781 /*
782 if (ret == E_NOMEM)
783 return -1;
784 */
785 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000786}
787
Eric Smith7c478942008-03-18 23:45:49 +0000788#if 0
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000789/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000790#define PARSER_FLAGS(flags) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000791 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
792 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Eric Smith7c478942008-03-18 23:45:49 +0000793#endif
794#if 1
Neal Norwitzca460d92006-09-06 06:28:06 +0000795/* Keep an example of flags with future keyword support. */
796#define PARSER_FLAGS(flags) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000797 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
798 PyPARSE_DONT_IMPLY_DEDENT : 0) \
799 | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
800 PyPARSE_PRINT_IS_FUNCTION : 0) \
801 | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
802 PyPARSE_UNICODE_LITERALS : 0) \
803 ) : 0)
Neal Norwitzca460d92006-09-06 06:28:06 +0000804#endif
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000805
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000806int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000807PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000808{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000809 PyObject *m, *d, *v, *w;
810 mod_ty mod;
811 PyArena *arena;
812 char *ps1 = "", *ps2 = "";
813 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000814
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000815 v = PySys_GetObject("ps1");
816 if (v != NULL) {
817 v = PyObject_Str(v);
818 if (v == NULL)
819 PyErr_Clear();
820 else if (PyString_Check(v))
821 ps1 = PyString_AsString(v);
822 }
823 w = PySys_GetObject("ps2");
824 if (w != NULL) {
825 w = PyObject_Str(w);
826 if (w == NULL)
827 PyErr_Clear();
828 else if (PyString_Check(w))
829 ps2 = PyString_AsString(w);
830 }
831 arena = PyArena_New();
832 if (arena == NULL) {
833 Py_XDECREF(v);
834 Py_XDECREF(w);
835 return -1;
836 }
837 mod = PyParser_ASTFromFile(fp, filename,
838 Py_single_input, ps1, ps2,
839 flags, &errcode, arena);
840 Py_XDECREF(v);
841 Py_XDECREF(w);
842 if (mod == NULL) {
843 PyArena_Free(arena);
844 if (errcode == E_EOF) {
845 PyErr_Clear();
846 return E_EOF;
847 }
848 PyErr_Print();
849 return -1;
850 }
851 m = PyImport_AddModule("__main__");
852 if (m == NULL) {
853 PyArena_Free(arena);
854 return -1;
855 }
856 d = PyModule_GetDict(m);
857 v = run_mod(mod, filename, d, d, flags, arena);
858 PyArena_Free(arena);
859 if (v == NULL) {
860 PyErr_Print();
861 return -1;
862 }
863 Py_DECREF(v);
864 if (Py_FlushLine())
865 PyErr_Clear();
866 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000867}
868
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000869/* Check whether a file maybe a pyc file: Look at the extension,
870 the file type, and, if we may close it, at the first few bytes. */
871
872static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000873maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000874{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000875 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
876 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000877
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000878 /* Only look into the file if we are allowed to close it, since
879 it then should also be seekable. */
880 if (closeit) {
881 /* Read only two bytes of the magic. If the file was opened in
882 text mode, the bytes 3 and 4 of the magic (\r\n) might not
883 be read as they are on disk. */
884 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
885 unsigned char buf[2];
886 /* Mess: In case of -x, the stream is NOT at its start now,
887 and ungetc() was used to push back the first newline,
888 which makes the current stream position formally undefined,
889 and a x-platform nightmare.
890 Unfortunately, we have no direct way to know whether -x
891 was specified. So we use a terrible hack: if the current
892 stream position is not 0, we assume -x was specified, and
893 give up. Bug 132850 on SourceForge spells out the
894 hopelessness of trying anything else (fseek and ftell
895 don't work predictably x-platform for text-mode files).
896 */
897 int ispyc = 0;
898 if (ftell(fp) == 0) {
899 if (fread(buf, 1, 2, fp) == 2 &&
900 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
901 ispyc = 1;
902 rewind(fp);
903 }
904 return ispyc;
905 }
906 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000907}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000908
Guido van Rossum0df002c2000-08-27 19:21:52 +0000909int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000910PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000911 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000912{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000913 PyObject *m, *d, *v;
914 const char *ext;
915 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000916
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000917 m = PyImport_AddModule("__main__");
918 if (m == NULL)
919 return -1;
920 d = PyModule_GetDict(m);
921 if (PyDict_GetItemString(d, "__file__") == NULL) {
922 PyObject *f = PyString_FromString(filename);
923 if (f == NULL)
924 return -1;
925 if (PyDict_SetItemString(d, "__file__", f) < 0) {
926 Py_DECREF(f);
927 return -1;
928 }
929 set_file_name = 1;
930 Py_DECREF(f);
931 }
932 len = strlen(filename);
933 ext = filename + len - (len > 4 ? 4 : 0);
934 if (maybe_pyc_file(fp, filename, ext, closeit)) {
935 /* Try to run a pyc file. First, re-open in binary */
936 if (closeit)
937 fclose(fp);
938 if ((fp = fopen(filename, "rb")) == NULL) {
939 fprintf(stderr, "python: Can't reopen .pyc file\n");
940 ret = -1;
941 goto done;
942 }
943 /* Turn on optimization if a .pyo file is given */
944 if (strcmp(ext, ".pyo") == 0)
945 Py_OptimizeFlag = 1;
946 v = run_pyc_file(fp, filename, d, d, flags);
947 } else {
948 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
949 closeit, flags);
950 }
951 if (v == NULL) {
952 PyErr_Print();
953 ret = -1;
954 goto done;
955 }
956 Py_DECREF(v);
957 if (Py_FlushLine())
958 PyErr_Clear();
959 ret = 0;
Georg Brandlaa2321b2007-03-07 00:40:28 +0000960 done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000961 if (set_file_name && PyDict_DelItemString(d, "__file__"))
962 PyErr_Clear();
963 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000964}
965
966int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000967PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000968{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000969 PyObject *m, *d, *v;
970 m = PyImport_AddModule("__main__");
971 if (m == NULL)
972 return -1;
973 d = PyModule_GetDict(m);
974 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
975 if (v == NULL) {
976 PyErr_Print();
977 return -1;
978 }
979 Py_DECREF(v);
980 if (Py_FlushLine())
981 PyErr_Clear();
982 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000983}
984
Barry Warsaw035574d1997-08-29 22:07:17 +0000985static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000986parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000987 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000988{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000989 long hold;
990 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +0000991
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000992 /* old style errors */
993 if (PyTuple_Check(err))
994 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
995 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000996
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000997 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +0000998
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000999 if (! (v = PyObject_GetAttrString(err, "msg")))
1000 goto finally;
1001 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001002
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001003 if (!(v = PyObject_GetAttrString(err, "filename")))
1004 goto finally;
1005 if (v == Py_None)
1006 *filename = NULL;
1007 else if (! (*filename = PyString_AsString(v)))
1008 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001009
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001010 Py_DECREF(v);
1011 if (!(v = PyObject_GetAttrString(err, "lineno")))
1012 goto finally;
1013 hold = PyInt_AsLong(v);
1014 Py_DECREF(v);
1015 v = NULL;
1016 if (hold < 0 && PyErr_Occurred())
1017 goto finally;
1018 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001019
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001020 if (!(v = PyObject_GetAttrString(err, "offset")))
1021 goto finally;
1022 if (v == Py_None) {
1023 *offset = -1;
1024 Py_DECREF(v);
1025 v = NULL;
1026 } else {
1027 hold = PyInt_AsLong(v);
1028 Py_DECREF(v);
1029 v = NULL;
1030 if (hold < 0 && PyErr_Occurred())
1031 goto finally;
1032 *offset = (int)hold;
1033 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001034
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001035 if (!(v = PyObject_GetAttrString(err, "text")))
1036 goto finally;
1037 if (v == Py_None)
1038 *text = NULL;
1039 else if (! (*text = PyString_AsString(v)))
1040 goto finally;
1041 Py_DECREF(v);
1042 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001043
1044finally:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001045 Py_XDECREF(v);
1046 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001047}
1048
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001049void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001050PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001051{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001052 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001053}
1054
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001055static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001056print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001057{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001058 char *nl;
1059 if (offset >= 0) {
1060 if (offset > 0 && offset == (int)strlen(text))
1061 offset--;
1062 for (;;) {
1063 nl = strchr(text, '\n');
1064 if (nl == NULL || nl-text >= offset)
1065 break;
1066 offset -= (int)(nl+1-text);
1067 text = nl+1;
1068 }
1069 while (*text == ' ' || *text == '\t') {
1070 text++;
1071 offset--;
1072 }
1073 }
1074 PyFile_WriteString(" ", f);
1075 PyFile_WriteString(text, f);
1076 if (*text == '\0' || text[strlen(text)-1] != '\n')
1077 PyFile_WriteString("\n", f);
1078 if (offset == -1)
1079 return;
1080 PyFile_WriteString(" ", f);
1081 offset--;
1082 while (offset > 0) {
1083 PyFile_WriteString(" ", f);
1084 offset--;
1085 }
1086 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001087}
1088
Guido van Rossum66e8e862001-03-23 17:54:43 +00001089static void
1090handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001091{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001092 PyObject *exception, *value, *tb;
1093 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001094
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001095 if (Py_InspectFlag)
1096 /* Don't exit if -i flag was given. This flag is set to 0
1097 * when entering interactive mode for inspecting. */
1098 return;
Georg Brandl49aafc92007-03-07 00:34:46 +00001099
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001100 PyErr_Fetch(&exception, &value, &tb);
1101 if (Py_FlushLine())
1102 PyErr_Clear();
1103 fflush(stdout);
1104 if (value == NULL || value == Py_None)
1105 goto done;
1106 if (PyExceptionInstance_Check(value)) {
1107 /* The error code should be in the `code' attribute. */
1108 PyObject *code = PyObject_GetAttrString(value, "code");
1109 if (code) {
1110 Py_DECREF(value);
1111 value = code;
1112 if (value == Py_None)
1113 goto done;
1114 }
1115 /* If we failed to dig out the 'code' attribute,
1116 just let the else clause below print the error. */
1117 }
1118 if (PyInt_Check(value))
1119 exitcode = (int)PyInt_AsLong(value);
1120 else {
Victor Stinnerc3e40e02010-05-25 22:40:38 +00001121 PyObject *sys_stderr = PySys_GetObject("stderr");
1122 if (sys_stderr != NULL && sys_stderr != Py_None) {
1123 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1124 } else {
1125 PyObject_Print(value, stderr, Py_PRINT_RAW);
1126 fflush(stderr);
1127 }
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001128 PySys_WriteStderr("\n");
1129 exitcode = 1;
1130 }
Tim Peterscf615b52003-04-19 18:47:02 +00001131 done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001132 /* Restore and clear the exception info, in order to properly decref
1133 * the exception, value, and traceback. If we just exit instead,
1134 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1135 * some finalizers from running.
1136 */
1137 PyErr_Restore(exception, value, tb);
1138 PyErr_Clear();
1139 Py_Exit(exitcode);
1140 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001141}
1142
1143void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001144PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001145{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001146 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001147
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001148 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1149 handle_system_exit();
1150 }
1151 PyErr_Fetch(&exception, &v, &tb);
1152 if (exception == NULL)
1153 return;
1154 PyErr_NormalizeException(&exception, &v, &tb);
1155 if (exception == NULL)
1156 return;
1157 /* Now we know v != NULL too */
1158 if (set_sys_last_vars) {
1159 PySys_SetObject("last_type", exception);
1160 PySys_SetObject("last_value", v);
1161 PySys_SetObject("last_traceback", tb);
1162 }
1163 hook = PySys_GetObject("excepthook");
1164 if (hook) {
1165 PyObject *args = PyTuple_Pack(3,
1166 exception, v, tb ? tb : Py_None);
1167 PyObject *result = PyEval_CallObject(hook, args);
1168 if (result == NULL) {
1169 PyObject *exception2, *v2, *tb2;
1170 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1171 handle_system_exit();
1172 }
1173 PyErr_Fetch(&exception2, &v2, &tb2);
1174 PyErr_NormalizeException(&exception2, &v2, &tb2);
1175 /* It should not be possible for exception2 or v2
1176 to be NULL. However PyErr_Display() can't
1177 tolerate NULLs, so just be safe. */
1178 if (exception2 == NULL) {
1179 exception2 = Py_None;
1180 Py_INCREF(exception2);
1181 }
1182 if (v2 == NULL) {
1183 v2 = Py_None;
1184 Py_INCREF(v2);
1185 }
1186 if (Py_FlushLine())
1187 PyErr_Clear();
1188 fflush(stdout);
1189 PySys_WriteStderr("Error in sys.excepthook:\n");
1190 PyErr_Display(exception2, v2, tb2);
1191 PySys_WriteStderr("\nOriginal exception was:\n");
1192 PyErr_Display(exception, v, tb);
1193 Py_DECREF(exception2);
1194 Py_DECREF(v2);
1195 Py_XDECREF(tb2);
1196 }
1197 Py_XDECREF(result);
1198 Py_XDECREF(args);
1199 } else {
1200 PySys_WriteStderr("sys.excepthook is missing\n");
1201 PyErr_Display(exception, v, tb);
1202 }
1203 Py_XDECREF(exception);
1204 Py_XDECREF(v);
1205 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001206}
1207
Richard Jones7b9558d2006-05-27 12:29:24 +00001208void
1209PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001210{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001211 int err = 0;
1212 PyObject *f = PySys_GetObject("stderr");
1213 Py_INCREF(value);
1214 if (f == NULL)
1215 fprintf(stderr, "lost sys.stderr\n");
1216 else {
1217 if (Py_FlushLine())
1218 PyErr_Clear();
1219 fflush(stdout);
1220 if (tb && tb != Py_None)
1221 err = PyTraceBack_Print(tb, f);
1222 if (err == 0 &&
1223 PyObject_HasAttrString(value, "print_file_and_line"))
1224 {
1225 PyObject *message;
1226 const char *filename, *text;
1227 int lineno, offset;
1228 if (!parse_syntax_error(value, &message, &filename,
1229 &lineno, &offset, &text))
1230 PyErr_Clear();
1231 else {
1232 char buf[10];
1233 PyFile_WriteString(" File \"", f);
1234 if (filename == NULL)
1235 PyFile_WriteString("<string>", f);
1236 else
1237 PyFile_WriteString(filename, f);
1238 PyFile_WriteString("\", line ", f);
1239 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1240 PyFile_WriteString(buf, f);
1241 PyFile_WriteString("\n", f);
1242 if (text != NULL)
1243 print_error_text(f, offset, text);
1244 Py_DECREF(value);
1245 value = message;
1246 /* Can't be bothered to check all those
1247 PyFile_WriteString() calls */
1248 if (PyErr_Occurred())
1249 err = -1;
1250 }
1251 }
1252 if (err) {
1253 /* Don't do anything else */
1254 }
1255 else if (PyExceptionClass_Check(exception)) {
1256 PyObject* moduleName;
1257 char* className = PyExceptionClass_Name(exception);
1258 if (className != NULL) {
1259 char *dot = strrchr(className, '.');
1260 if (dot != NULL)
1261 className = dot+1;
1262 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001263
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001264 moduleName = PyObject_GetAttrString(exception, "__module__");
1265 if (moduleName == NULL)
1266 err = PyFile_WriteString("<unknown>", f);
1267 else {
1268 char* modstr = PyString_AsString(moduleName);
1269 if (modstr && strcmp(modstr, "exceptions"))
1270 {
1271 err = PyFile_WriteString(modstr, f);
1272 err += PyFile_WriteString(".", f);
1273 }
1274 Py_DECREF(moduleName);
1275 }
1276 if (err == 0) {
1277 if (className == NULL)
1278 err = PyFile_WriteString("<unknown>", f);
1279 else
1280 err = PyFile_WriteString(className, f);
1281 }
1282 }
1283 else
1284 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1285 if (err == 0 && (value != Py_None)) {
1286 PyObject *s = PyObject_Str(value);
1287 /* only print colon if the str() of the
1288 object is not the empty string
1289 */
1290 if (s == NULL)
1291 err = -1;
1292 else if (!PyString_Check(s) ||
1293 PyString_GET_SIZE(s) != 0)
1294 err = PyFile_WriteString(": ", f);
1295 if (err == 0)
1296 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1297 Py_XDECREF(s);
1298 }
1299 /* try to write a newline in any case */
1300 err += PyFile_WriteString("\n", f);
1301 }
1302 Py_DECREF(value);
1303 /* If an error happened here, don't show it.
1304 XXX This is wrong, but too many callers rely on this behavior. */
1305 if (err != 0)
1306 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001307}
1308
Guido van Rossum82598051997-03-05 00:20:32 +00001309PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001310PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001311 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001312{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001313 PyObject *ret = NULL;
1314 mod_ty mod;
1315 PyArena *arena = PyArena_New();
1316 if (arena == NULL)
1317 return NULL;
1318
1319 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1320 if (mod != NULL)
1321 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1322 PyArena_Free(arena);
1323 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001324}
1325
1326PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001327PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001328 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001329{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001330 PyObject *ret;
1331 mod_ty mod;
1332 PyArena *arena = PyArena_New();
1333 if (arena == NULL)
1334 return NULL;
1335
1336 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1337 flags, NULL, arena);
1338 if (closeit)
1339 fclose(fp);
1340 if (mod == NULL) {
1341 PyArena_Free(arena);
1342 return NULL;
1343 }
1344 ret = run_mod(mod, filename, globals, locals, flags, arena);
1345 PyArena_Free(arena);
1346 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001347}
1348
Guido van Rossum82598051997-03-05 00:20:32 +00001349static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001350run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001351 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001352{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001353 PyCodeObject *co;
1354 PyObject *v;
1355 co = PyAST_Compile(mod, filename, flags, arena);
1356 if (co == NULL)
1357 return NULL;
1358 v = PyEval_EvalCode(co, globals, locals);
1359 Py_DECREF(co);
1360 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001361}
1362
Guido van Rossum82598051997-03-05 00:20:32 +00001363static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001364run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001365 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001366{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001367 PyCodeObject *co;
1368 PyObject *v;
1369 long magic;
1370 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001371
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001372 magic = PyMarshal_ReadLongFromFile(fp);
1373 if (magic != PyImport_GetMagicNumber()) {
1374 PyErr_SetString(PyExc_RuntimeError,
1375 "Bad magic number in .pyc file");
1376 return NULL;
1377 }
1378 (void) PyMarshal_ReadLongFromFile(fp);
1379 v = PyMarshal_ReadLastObjectFromFile(fp);
1380 fclose(fp);
1381 if (v == NULL || !PyCode_Check(v)) {
1382 Py_XDECREF(v);
1383 PyErr_SetString(PyExc_RuntimeError,
1384 "Bad code object in .pyc file");
1385 return NULL;
1386 }
1387 co = (PyCodeObject *)v;
1388 v = PyEval_EvalCode(co, globals, locals);
1389 if (v && flags)
1390 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1391 Py_DECREF(co);
1392 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001393}
1394
Guido van Rossum82598051997-03-05 00:20:32 +00001395PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001396Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001397 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001398{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001399 PyCodeObject *co;
1400 mod_ty mod;
1401 PyArena *arena = PyArena_New();
1402 if (arena == NULL)
1403 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001404
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001405 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1406 if (mod == NULL) {
1407 PyArena_Free(arena);
1408 return NULL;
1409 }
1410 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1411 PyObject *result = PyAST_mod2obj(mod);
1412 PyArena_Free(arena);
1413 return result;
1414 }
1415 co = PyAST_Compile(mod, filename, flags, arena);
1416 PyArena_Free(arena);
1417 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001418}
1419
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001420struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001421Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001422{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001423 struct symtable *st;
1424 mod_ty mod;
1425 PyCompilerFlags flags;
1426 PyArena *arena = PyArena_New();
1427 if (arena == NULL)
1428 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001429
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001430 flags.cf_flags = 0;
Christian Heimes7f23d862008-03-26 22:51:58 +00001431
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001432 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1433 if (mod == NULL) {
1434 PyArena_Free(arena);
1435 return NULL;
1436 }
1437 st = PySymtable_Build(mod, filename, 0);
1438 PyArena_Free(arena);
1439 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001440}
1441
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001442/* Preferred access to parser is through AST. */
1443mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001444PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001445 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001446{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001447 mod_ty mod;
1448 PyCompilerFlags localflags;
1449 perrdetail err;
1450 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001451
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001452 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1453 &_PyParser_Grammar, start, &err,
1454 &iflags);
1455 if (flags == NULL) {
1456 localflags.cf_flags = 0;
1457 flags = &localflags;
1458 }
1459 if (n) {
1460 flags->cf_flags |= iflags & PyCF_MASK;
1461 mod = PyAST_FromNode(n, flags, filename, arena);
1462 PyNode_Free(n);
1463 return mod;
1464 }
1465 else {
1466 err_input(&err);
1467 return NULL;
1468 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469}
1470
1471mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001472PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001473 char *ps2, PyCompilerFlags *flags, int *errcode,
1474 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001475{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001476 mod_ty mod;
1477 PyCompilerFlags localflags;
1478 perrdetail err;
1479 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001480
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001481 node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
1482 start, ps1, ps2, &err, &iflags);
1483 if (flags == NULL) {
1484 localflags.cf_flags = 0;
1485 flags = &localflags;
1486 }
1487 if (n) {
1488 flags->cf_flags |= iflags & PyCF_MASK;
1489 mod = PyAST_FromNode(n, flags, filename, arena);
1490 PyNode_Free(n);
1491 return mod;
1492 }
1493 else {
1494 err_input(&err);
1495 if (errcode)
1496 *errcode = err.error;
1497 return NULL;
1498 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001499}
1500
Guido van Rossuma110aa61994-08-29 12:50:44 +00001501/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001502
Guido van Rossuma110aa61994-08-29 12:50:44 +00001503node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001504PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001505{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001506 perrdetail err;
1507 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1508 start, NULL, NULL, &err, flags);
1509 if (n == NULL)
1510 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001511
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001512 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001513}
1514
Guido van Rossuma110aa61994-08-29 12:50:44 +00001515/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001516
Guido van Rossuma110aa61994-08-29 12:50:44 +00001517node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001518PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001519{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001520 perrdetail err;
1521 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1522 start, &err, flags);
1523 if (n == NULL)
1524 err_input(&err);
1525 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001526}
1527
1528node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001529PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001530 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001531{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001532 perrdetail err;
1533 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1534 &_PyParser_Grammar, start, &err, flags);
1535 if (n == NULL)
1536 err_input(&err);
1537 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001538}
1539
1540node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001541PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001542{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001543 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001544}
1545
Guido van Rossum66ebd912003-04-17 16:02:26 +00001546/* May want to move a more generalized form of this to parsetok.c or
1547 even parser modules. */
1548
1549void
1550PyParser_SetError(perrdetail *err)
1551{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001552 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001553}
1554
Guido van Rossuma110aa61994-08-29 12:50:44 +00001555/* Set the error appropriate to the given input error code (see errcode.h) */
1556
1557static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001558err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001559{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001560 PyObject *v, *w, *errtype;
1561 PyObject* u = NULL;
1562 char *msg = NULL;
1563 errtype = PyExc_SyntaxError;
1564 switch (err->error) {
1565 case E_ERROR:
1566 return;
1567 case E_SYNTAX:
1568 errtype = PyExc_IndentationError;
1569 if (err->expected == INDENT)
1570 msg = "expected an indented block";
1571 else if (err->token == INDENT)
1572 msg = "unexpected indent";
1573 else if (err->token == DEDENT)
1574 msg = "unexpected unindent";
1575 else {
1576 errtype = PyExc_SyntaxError;
1577 msg = "invalid syntax";
1578 }
1579 break;
1580 case E_TOKEN:
1581 msg = "invalid token";
1582 break;
1583 case E_EOFS:
1584 msg = "EOF while scanning triple-quoted string literal";
1585 break;
1586 case E_EOLS:
1587 msg = "EOL while scanning string literal";
1588 break;
1589 case E_INTR:
1590 if (!PyErr_Occurred())
1591 PyErr_SetNone(PyExc_KeyboardInterrupt);
1592 goto cleanup;
1593 case E_NOMEM:
1594 PyErr_NoMemory();
1595 goto cleanup;
1596 case E_EOF:
1597 msg = "unexpected EOF while parsing";
1598 break;
1599 case E_TABSPACE:
1600 errtype = PyExc_TabError;
1601 msg = "inconsistent use of tabs and spaces in indentation";
1602 break;
1603 case E_OVERFLOW:
1604 msg = "expression too long";
1605 break;
1606 case E_DEDENT:
1607 errtype = PyExc_IndentationError;
1608 msg = "unindent does not match any outer indentation level";
1609 break;
1610 case E_TOODEEP:
1611 errtype = PyExc_IndentationError;
1612 msg = "too many levels of indentation";
1613 break;
1614 case E_DECODE: {
1615 PyObject *type, *value, *tb;
1616 PyErr_Fetch(&type, &value, &tb);
1617 if (value != NULL) {
1618 u = PyObject_Str(value);
1619 if (u != NULL) {
1620 msg = PyString_AsString(u);
1621 }
1622 }
1623 if (msg == NULL)
1624 msg = "unknown decode error";
1625 Py_XDECREF(type);
1626 Py_XDECREF(value);
1627 Py_XDECREF(tb);
1628 break;
1629 }
1630 case E_LINECONT:
1631 msg = "unexpected character after line continuation character";
1632 break;
1633 default:
1634 fprintf(stderr, "error=%d\n", err->error);
1635 msg = "unknown parsing error";
1636 break;
1637 }
1638 v = Py_BuildValue("(ziiz)", err->filename,
1639 err->lineno, err->offset, err->text);
1640 w = NULL;
1641 if (v != NULL)
1642 w = Py_BuildValue("(sO)", msg, v);
1643 Py_XDECREF(u);
1644 Py_XDECREF(v);
1645 PyErr_SetObject(errtype, w);
1646 Py_XDECREF(w);
Georg Brandl1ad108d2008-07-19 10:08:55 +00001647cleanup:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001648 if (err->text != NULL) {
1649 PyObject_FREE(err->text);
1650 err->text = NULL;
1651 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001652}
1653
1654/* Print fatal error message and abort */
1655
1656void
Tim Peters7c321a82002-07-09 02:57:01 +00001657Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001658{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001659 fprintf(stderr, "Fatal Python error: %s\n", msg);
1660 fflush(stderr); /* it helps in Windows debug build */
Jesse Noller70b11f02009-03-31 22:25:20 +00001661
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001662#ifdef MS_WINDOWS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001663 {
1664 size_t len = strlen(msg);
1665 WCHAR* buffer;
1666 size_t i;
Georg Brandl734373c2009-01-03 21:55:17 +00001667
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001668 /* Convert the message to wchar_t. This uses a simple one-to-one
1669 conversion, assuming that the this error message actually uses ASCII
1670 only. If this ceases to be true, we will have to convert. */
1671 buffer = alloca( (len+1) * (sizeof *buffer));
1672 for( i=0; i<=len; ++i)
1673 buffer[i] = msg[i];
1674 OutputDebugStringW(L"Fatal Python error: ");
1675 OutputDebugStringW(buffer);
1676 OutputDebugStringW(L"\n");
1677 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001678#ifdef _DEBUG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001679 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001680#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001681#endif /* MS_WINDOWS */
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001682 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001683}
1684
1685/* Clean up and exit */
1686
Guido van Rossuma110aa61994-08-29 12:50:44 +00001687#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001688#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001689#endif
1690
Antoine Pitrou9aece752009-10-27 12:48:52 +00001691/* Wait until threading._shutdown completes, provided
1692 the threading module was imported in the first place.
1693 The shutdown routine will wait until all non-daemon
1694 "threading" threads have completed. */
1695static void
1696wait_for_thread_shutdown(void)
1697{
1698#ifdef WITH_THREAD
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001699 PyObject *result;
1700 PyThreadState *tstate = PyThreadState_GET();
1701 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1702 "threading");
1703 if (threading == NULL) {
1704 /* threading not imported */
1705 PyErr_Clear();
1706 return;
1707 }
1708 result = PyObject_CallMethod(threading, "_shutdown", "");
1709 if (result == NULL)
1710 PyErr_WriteUnraisable(threading);
1711 else
1712 Py_DECREF(result);
1713 Py_DECREF(threading);
Antoine Pitrou9aece752009-10-27 12:48:52 +00001714#endif
1715}
1716
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001717#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001718static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001719static int nexitfuncs = 0;
1720
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001721int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001722{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001723 if (nexitfuncs >= NEXITFUNCS)
1724 return -1;
1725 exitfuncs[nexitfuncs++] = func;
1726 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00001727}
1728
Guido van Rossumcc283f51997-08-05 02:22:03 +00001729static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001730call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001731{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001732 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001733
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001734 if (exitfunc) {
1735 PyObject *res;
1736 Py_INCREF(exitfunc);
1737 PySys_SetObject("exitfunc", (PyObject *)NULL);
1738 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1739 if (res == NULL) {
1740 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1741 PySys_WriteStderr("Error in sys.exitfunc:\n");
1742 }
1743 PyErr_Print();
1744 }
1745 Py_DECREF(exitfunc);
1746 }
Guido van Rossum59bff391992-09-03 20:28:00 +00001747
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001748 if (Py_FlushLine())
1749 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001750}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001751
Guido van Rossumcc283f51997-08-05 02:22:03 +00001752static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001753call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001754{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001755 while (nexitfuncs > 0)
1756 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001757
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001758 fflush(stdout);
1759 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001760}
1761
1762void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001763Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001764{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001765 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001766
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001767 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001768}
1769
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001770static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001771initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001772{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001773#ifdef SIGPIPE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001774 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001775#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001776#ifdef SIGXFZ
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001777 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001778#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001779#ifdef SIGXFSZ
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001780 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001781#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001782 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001783}
1784
Guido van Rossum7433b121997-02-14 19:45:36 +00001785
1786/*
1787 * The file descriptor fd is considered ``interactive'' if either
1788 * a) isatty(fd) is TRUE, or
1789 * b) the -i flag was given, and the filename associated with
1790 * the descriptor is NULL or "<stdin>" or "???".
1791 */
1792int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001793Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001794{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001795 if (isatty((int)fileno(fp)))
1796 return 1;
1797 if (!Py_InteractiveFlag)
1798 return 0;
1799 return (filename == NULL) ||
1800 (strcmp(filename, "<stdin>") == 0) ||
1801 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00001802}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001803
1804
Tim Petersd08e3822003-04-17 15:24:21 +00001805#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001806#if defined(WIN32) && defined(_MSC_VER)
1807
1808/* Stack checking for Microsoft C */
1809
1810#include <malloc.h>
1811#include <excpt.h>
1812
Fred Drakee8de31c2000-08-31 05:38:39 +00001813/*
1814 * Return non-zero when we run out of memory on the stack; zero otherwise.
1815 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001816int
Fred Drake399739f2000-08-31 05:52:44 +00001817PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001818{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001819 __try {
1820 /* alloca throws a stack overflow exception if there's
1821 not enough space left on the stack */
1822 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1823 return 0;
1824 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1825 EXCEPTION_EXECUTE_HANDLER :
1826 EXCEPTION_CONTINUE_SEARCH) {
1827 int errcode = _resetstkoflw();
1828 if (errcode == 0)
1829 {
1830 Py_FatalError("Could not reset the stack!");
1831 }
1832 }
1833 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001834}
1835
1836#endif /* WIN32 && _MSC_VER */
1837
1838/* Alternate implementations can be added here... */
1839
1840#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001841
1842
1843/* Wrappers around sigaction() or signal(). */
1844
1845PyOS_sighandler_t
1846PyOS_getsig(int sig)
1847{
1848#ifdef HAVE_SIGACTION
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001849 struct sigaction context;
1850 if (sigaction(sig, NULL, &context) == -1)
1851 return SIG_ERR;
1852 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001853#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001854 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001855/* Special signal handling for the secure CRT in Visual Studio 2005 */
1856#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001857 switch (sig) {
1858 /* Only these signals are valid */
1859 case SIGINT:
1860 case SIGILL:
1861 case SIGFPE:
1862 case SIGSEGV:
1863 case SIGTERM:
1864 case SIGBREAK:
1865 case SIGABRT:
1866 break;
1867 /* Don't call signal() with other values or it will assert */
1868 default:
1869 return SIG_ERR;
1870 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001871#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001872 handler = signal(sig, SIG_IGN);
1873 if (handler != SIG_ERR)
1874 signal(sig, handler);
1875 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001876#endif
1877}
1878
1879PyOS_sighandler_t
1880PyOS_setsig(int sig, PyOS_sighandler_t handler)
1881{
1882#ifdef HAVE_SIGACTION
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001883 /* Some code in Modules/signalmodule.c depends on sigaction() being
1884 * used here if HAVE_SIGACTION is defined. Fix that if this code
1885 * changes to invalidate that assumption.
1886 */
1887 struct sigaction context, ocontext;
1888 context.sa_handler = handler;
1889 sigemptyset(&context.sa_mask);
1890 context.sa_flags = 0;
1891 if (sigaction(sig, &context, &ocontext) == -1)
1892 return SIG_ERR;
1893 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001894#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001895 PyOS_sighandler_t oldhandler;
1896 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001897#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001898 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001899#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001900 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001901#endif
1902}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001903
1904/* Deprecated C API functions still provided for binary compatiblity */
1905
1906#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001907PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001908PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1909{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001910 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001911}
1912
Thomas Heller1b046642006-04-18 18:51:06 +00001913#undef PyParser_SimpleParseString
1914PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001915PyParser_SimpleParseString(const char *str, int start)
1916{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001917 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001918}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001919
Thomas Heller1b046642006-04-18 18:51:06 +00001920#undef PyRun_AnyFile
1921PyAPI_FUNC(int)
1922PyRun_AnyFile(FILE *fp, const char *name)
1923{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001924 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001925}
1926
1927#undef PyRun_AnyFileEx
1928PyAPI_FUNC(int)
1929PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1930{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001931 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001932}
1933
1934#undef PyRun_AnyFileFlags
1935PyAPI_FUNC(int)
1936PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1937{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001938 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001939}
1940
1941#undef PyRun_File
1942PyAPI_FUNC(PyObject *)
1943PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1944{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001945 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001946}
1947
1948#undef PyRun_FileEx
1949PyAPI_FUNC(PyObject *)
1950PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1951{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001952 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001953}
1954
1955#undef PyRun_FileFlags
1956PyAPI_FUNC(PyObject *)
1957PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001958 PyCompilerFlags *flags)
Thomas Heller1b046642006-04-18 18:51:06 +00001959{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001960 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001961}
1962
1963#undef PyRun_SimpleFile
1964PyAPI_FUNC(int)
1965PyRun_SimpleFile(FILE *f, const char *p)
1966{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001967 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001968}
1969
1970#undef PyRun_SimpleFileEx
1971PyAPI_FUNC(int)
1972PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1973{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001974 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001975}
1976
1977
1978#undef PyRun_String
1979PyAPI_FUNC(PyObject *)
1980PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1981{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001982 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001983}
1984
1985#undef PyRun_SimpleString
1986PyAPI_FUNC(int)
1987PyRun_SimpleString(const char *s)
1988{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001989 return PyRun_SimpleStringFlags(s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001990}
1991
1992#undef Py_CompileString
1993PyAPI_FUNC(PyObject *)
1994Py_CompileString(const char *str, const char *p, int s)
1995{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001996 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001997}
1998
1999#undef PyRun_InteractiveOne
2000PyAPI_FUNC(int)
2001PyRun_InteractiveOne(FILE *f, const char *p)
2002{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002003 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002004}
2005
2006#undef PyRun_InteractiveLoop
2007PyAPI_FUNC(int)
2008PyRun_InteractiveLoop(FILE *f, const char *p)
2009{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002010 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002011}
2012
Anthony Baxterac6bd462006-04-13 02:06:09 +00002013#ifdef __cplusplus
2014}
2015#endif
2016