blob: a2663c70671d3922d5098e748484ea2a86851402 [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);
Barry Warsaw1e13eb02012-02-20 20:42:21 -050070extern void _PyRandom_Init(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000071
Mark Hammond8d98d2c2003-04-19 15:41:53 +000072#ifdef WITH_THREAD
73extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
74extern void _PyGILState_Fini(void);
75#endif /* WITH_THREAD */
76
Guido van Rossum82598051997-03-05 00:20:32 +000077int Py_DebugFlag; /* Needed by parser.c */
78int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000079int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl49aafc92007-03-07 00:34:46 +000080int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000081int Py_NoSiteFlag; /* Suppress 'import site' */
Christian Heimes1a6387e2008-03-26 12:49:49 +000082int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Georg Brandl2da0fce2008-01-07 17:09:35 +000083int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000084int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000085int Py_FrozenFlag; /* Needed by getpath.c */
Guido van Rossumb16d1972000-05-01 17:55:15 +000086int Py_UnicodeFlag = 0; /* Needed by compile.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000087int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Tim Peters3caca232001-12-06 06:23:26 +000088/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
89 on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
90 true divisions (which they will be in 2.3). */
91int _Py_QnewFlag = 0;
Christian Heimesaf748c32008-05-06 22:41:46 +000092int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Barry Warsaw1e13eb02012-02-20 20:42:21 -050093int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000094
Brett Cannone9746892008-04-12 23:44:07 +000095/* PyModule_GetWarningsModule is no longer necessary as of 2.6
96since _warnings is builtin. This API should not be used. */
97PyObject *
98PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000099{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000100 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000101}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000102
Guido van Rossum25ce5661997-08-02 03:10:38 +0000103static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000104
Thomas Wouters7e474022000-07-16 12:04:32 +0000105/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106
107int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000108Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000110 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111}
112
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113/* Global initializations. Can be undone by Py_Finalize(). Don't
114 call this twice without an intervening Py_Finalize() call. When
115 initializations fail, a fatal error is issued and the function does
116 not return. On return, the first thread and interpreter state have
117 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119 Locking: you must hold the interpreter lock while calling this.
120 (If the lock has not yet been initialized, that's equivalent to
121 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000125static int
126add_flag(int flag, const char *envs)
127{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000128 int env = atoi(envs);
129 if (flag < env)
130 flag = env;
131 if (flag < 1)
132 flag = 1;
133 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000134}
135
Guido van Rossuma027efa1997-05-05 20:56:21 +0000136void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000137Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000138{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000139 PyInterpreterState *interp;
140 PyThreadState *tstate;
141 PyObject *bimod, *sysmod;
142 char *p;
143 char *icodeset = NULL; /* On Windows, input codeset may theoretically
144 differ from output codeset. */
145 char *codeset = NULL;
146 char *errors = NULL;
147 int free_codeset = 0;
148 int overridden = 0;
149 PyObject *sys_stream, *sys_isatty;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000150#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000151 char *saved_locale, *loc_codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000152#endif
Martin v. Löwis99815892008-06-01 07:20:46 +0000153#ifdef MS_WINDOWS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000154 char ibuf[128];
155 char buf[128];
Martin v. Löwis99815892008-06-01 07:20:46 +0000156#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000157 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000158
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000159 if (initialized)
160 return;
161 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000162
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000163 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
164 Py_DebugFlag = add_flag(Py_DebugFlag, p);
165 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
166 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
167 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
168 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
169 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
170 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500171 /* The variable is only tested for existence here; _PyRandom_Init will
172 check its value further. */
173 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
174 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
175
176 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000177
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000178 interp = PyInterpreterState_New();
179 if (interp == NULL)
180 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000181
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000182 tstate = PyThreadState_New(interp);
183 if (tstate == NULL)
184 Py_FatalError("Py_Initialize: can't make first thread");
185 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000186
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000187 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000188
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000189 if (!_PyFrame_Init())
190 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000191
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000192 if (!_PyInt_Init())
193 Py_FatalError("Py_Initialize: can't init ints");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000194
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000195 if (!PyByteArray_Init())
196 Py_FatalError("Py_Initialize: can't init bytearray");
Christian Heimes1a6387e2008-03-26 12:49:49 +0000197
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000198 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000199
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000200 interp->modules = PyDict_New();
201 if (interp->modules == NULL)
202 Py_FatalError("Py_Initialize: can't make modules dictionary");
203 interp->modules_reloading = PyDict_New();
204 if (interp->modules_reloading == NULL)
205 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000206
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000207#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000208 /* Init Unicode implementation; relies on the codec registry */
209 _PyUnicode_Init();
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000210#endif
Guido van Rossumc94044c2000-03-10 23:03:54 +0000211
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000212 bimod = _PyBuiltin_Init();
213 if (bimod == NULL)
214 Py_FatalError("Py_Initialize: can't initialize __builtin__");
215 interp->builtins = PyModule_GetDict(bimod);
216 if (interp->builtins == NULL)
217 Py_FatalError("Py_Initialize: can't initialize builtins dict");
218 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000219
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000220 sysmod = _PySys_Init();
221 if (sysmod == NULL)
222 Py_FatalError("Py_Initialize: can't initialize sys");
223 interp->sysdict = PyModule_GetDict(sysmod);
224 if (interp->sysdict == NULL)
225 Py_FatalError("Py_Initialize: can't initialize sys dict");
226 Py_INCREF(interp->sysdict);
227 _PyImport_FixupExtension("sys", "sys");
228 PySys_SetPath(Py_GetPath());
229 PyDict_SetItemString(interp->sysdict, "modules",
230 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000231
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000232 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000233
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000234 /* initialize builtin exceptions */
235 _PyExc_Init();
236 _PyImport_FixupExtension("exceptions", "exceptions");
Barry Warsawf242aa02000-05-25 23:09:49 +0000237
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000238 /* phase 2 of builtins */
239 _PyImport_FixupExtension("__builtin__", "__builtin__");
Barry Warsaw035574d1997-08-29 22:07:17 +0000240
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000241 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000242
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000243 if (install_sigs)
244 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000245
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000246 /* Initialize warnings. */
247 _PyWarnings_Init();
248 if (PySys_HasWarnOptions()) {
249 PyObject *warnings_module = PyImport_ImportModule("warnings");
250 if (!warnings_module)
251 PyErr_Clear();
252 Py_XDECREF(warnings_module);
253 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000254
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000255 initmain(); /* Module __main__ */
256
257 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000258#ifdef WITH_THREAD
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000259 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000260#endif /* WITH_THREAD */
261
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000262 if (!Py_NoSiteFlag)
263 initsite(); /* Module site */
Victor Stinnerea164292010-03-21 14:02:32 +0000264
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000265 if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
266 p = icodeset = codeset = strdup(p);
267 free_codeset = 1;
268 errors = strchr(p, ':');
269 if (errors) {
270 *errors = '\0';
271 errors++;
272 }
273 overridden = 1;
274 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000275
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000276#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000277 /* On Unix, set the file system encoding according to the
278 user's preference, if the CODESET names a well-known
279 Python codec, and Py_FileSystemDefaultEncoding isn't
280 initialized by other means. Also set the encoding of
281 stdin and stdout if these are terminals, unless overridden. */
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000282
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000283 if (!overridden || !Py_FileSystemDefaultEncoding) {
284 saved_locale = strdup(setlocale(LC_CTYPE, NULL));
285 setlocale(LC_CTYPE, "");
286 loc_codeset = nl_langinfo(CODESET);
287 if (loc_codeset && *loc_codeset) {
288 PyObject *enc = PyCodec_Encoder(loc_codeset);
289 if (enc) {
290 loc_codeset = strdup(loc_codeset);
291 Py_DECREF(enc);
292 } else {
293 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
294 PyErr_Clear();
295 loc_codeset = NULL;
296 } else {
297 PyErr_Print();
298 exit(1);
299 }
300 }
301 } else
302 loc_codeset = NULL;
303 setlocale(LC_CTYPE, saved_locale);
304 free(saved_locale);
Martin v. Löwis99815892008-06-01 07:20:46 +0000305
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000306 if (!overridden) {
307 codeset = icodeset = loc_codeset;
308 free_codeset = 1;
309 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000310
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000311 /* Initialize Py_FileSystemDefaultEncoding from
312 locale even if PYTHONIOENCODING is set. */
313 if (!Py_FileSystemDefaultEncoding) {
314 Py_FileSystemDefaultEncoding = loc_codeset;
315 if (!overridden)
316 free_codeset = 0;
317 }
318 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000319#endif
320
321#ifdef MS_WINDOWS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000322 if (!overridden) {
323 icodeset = ibuf;
324 codeset = buf;
325 sprintf(ibuf, "cp%d", GetConsoleCP());
326 sprintf(buf, "cp%d", GetConsoleOutputCP());
327 }
Martin v. Löwis99815892008-06-01 07:20:46 +0000328#endif
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000329
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000330 if (codeset) {
331 sys_stream = PySys_GetObject("stdin");
332 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
333 if (!sys_isatty)
334 PyErr_Clear();
335 if ((overridden ||
336 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
337 PyFile_Check(sys_stream)) {
338 if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
339 Py_FatalError("Cannot set codeset of stdin");
340 }
341 Py_XDECREF(sys_isatty);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000342
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000343 sys_stream = PySys_GetObject("stdout");
344 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
345 if (!sys_isatty)
346 PyErr_Clear();
347 if ((overridden ||
348 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
349 PyFile_Check(sys_stream)) {
350 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
351 Py_FatalError("Cannot set codeset of stdout");
352 }
353 Py_XDECREF(sys_isatty);
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000354
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000355 sys_stream = PySys_GetObject("stderr");
356 sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
357 if (!sys_isatty)
358 PyErr_Clear();
359 if((overridden ||
360 (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
361 PyFile_Check(sys_stream)) {
362 if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
363 Py_FatalError("Cannot set codeset of stderr");
364 }
365 Py_XDECREF(sys_isatty);
Martin v. Löwisea62d252006-04-03 10:56:49 +0000366
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000367 if (free_codeset)
368 free(codeset);
369 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000370}
371
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000372void
373Py_Initialize(void)
374{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000375 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000376}
377
378
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000379#ifdef COUNT_ALLOCS
Martin v. Löwis45294a92006-04-18 06:24:08 +0000380extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000381#endif
382
Guido van Rossum25ce5661997-08-02 03:10:38 +0000383/* Undo the effect of Py_Initialize().
384
385 Beware: if multiple interpreter and/or thread states exist, these
386 are not wiped out; only the current thread and interpreter state
387 are deleted. But since everything else is deleted, those other
388 interpreter and thread states should no longer be used.
389
390 (XXX We should do better, e.g. wipe out all interpreters and
391 threads.)
392
393 Locking: as above.
394
395*/
396
397void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000398Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000399{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000400 PyInterpreterState *interp;
401 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000402
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000403 if (!initialized)
404 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000405
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000406 wait_for_thread_shutdown();
Antoine Pitrou9aece752009-10-27 12:48:52 +0000407
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000408 /* The interpreter is still entirely intact at this point, and the
409 * exit funcs may be relying on that. In particular, if some thread
410 * or exit func is still waiting to do an import, the import machinery
411 * expects Py_IsInitialized() to return true. So don't say the
412 * interpreter is uninitialized until after the exit funcs have run.
413 * Note that Threading.py uses an exit func to do a join on all the
414 * threads created thru it, so this also protects pending imports in
415 * the threads created via Threading.
416 */
417 call_sys_exitfunc();
418 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000419
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000420 /* Get current thread state and interpreter pointer */
421 tstate = PyThreadState_GET();
422 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000423
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000424 /* Disable signal handling */
425 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000426
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000427 /* Clear type lookup cache */
428 PyType_ClearCache();
Christian Heimes908caac2008-01-27 23:34:59 +0000429
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000430 /* Collect garbage. This may call finalizers; it's nice to call these
431 * before all modules are destroyed.
432 * XXX If a __del__ or weakref callback is triggered here, and tries to
433 * XXX import a module, bad things can happen, because Python no
434 * XXX longer believes it's initialized.
435 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
436 * XXX is easy to provoke that way. I've also seen, e.g.,
437 * XXX Exception exceptions.ImportError: 'No module named sha'
438 * XXX in <function callback at 0x008F5718> ignored
439 * XXX but I'm unclear on exactly how that one happens. In any case,
440 * XXX I haven't seen a real-life report of either of these.
441 */
442 PyGC_Collect();
Martin v. Löwis45294a92006-04-18 06:24:08 +0000443#ifdef COUNT_ALLOCS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000444 /* With COUNT_ALLOCS, it helps to run GC multiple times:
445 each collection might release some types from the type
446 list, so they become garbage. */
447 while (PyGC_Collect() > 0)
448 /* nothing */;
Martin v. Löwis45294a92006-04-18 06:24:08 +0000449#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000450
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000451 /* Destroy all modules */
452 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000453
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000454 /* Collect final garbage. This disposes of cycles created by
455 * new-style class definitions, for example.
456 * XXX This is disabled because it caused too many problems. If
457 * XXX a __del__ or weakref callback triggers here, Python code has
458 * XXX a hard time running, because even the sys module has been
459 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
460 * XXX One symptom is a sequence of information-free messages
461 * XXX coming from threads (if a __del__ or callback is invoked,
462 * XXX other threads can execute too, and any exception they encounter
463 * XXX triggers a comedy of errors as subsystem after subsystem
464 * XXX fails to find what it *expects* to find in sys to help report
465 * XXX the exception and consequent unexpected failures). I've also
466 * XXX seen segfaults then, after adding print statements to the
467 * XXX Python code getting called.
468 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000469#if 0
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000470 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000471#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000472
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000473 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
474 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000475
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000476 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000477#ifdef COUNT_ALLOCS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000478 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000479#endif
480
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000481 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000482
Tim Peters9cf25ce2003-04-17 15:21:01 +0000483#ifdef Py_TRACE_REFS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000484 /* Display all objects still alive -- this can invoke arbitrary
485 * __repr__ overrides, so requires a mostly-intact interpreter.
486 * Alas, a lot of stuff may still be alive now that will be cleaned
487 * up later.
488 */
489 if (Py_GETENV("PYTHONDUMPREFS"))
490 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000491#endif /* Py_TRACE_REFS */
492
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000493 /* Clear interpreter state */
494 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000495
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000496 /* Now we decref the exception classes. After this point nothing
497 can raise an exception. That's okay, because each Fini() method
498 below has been checked to make sure no exceptions are ever
499 raised.
500 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000501
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000502 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000503
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000504 /* Cleanup auto-thread-state */
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000505#ifdef WITH_THREAD
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000506 _PyGILState_Fini();
Amaury Forgeot d'Arc025c3472007-11-29 23:35:25 +0000507#endif /* WITH_THREAD */
508
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000509 /* Delete current thread */
510 PyThreadState_Swap(NULL);
511 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000512
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000513 /* Sundry finalizers */
514 PyMethod_Fini();
515 PyFrame_Fini();
516 PyCFunction_Fini();
517 PyTuple_Fini();
518 PyList_Fini();
519 PySet_Fini();
520 PyString_Fini();
521 PyByteArray_Fini();
522 PyInt_Fini();
523 PyFloat_Fini();
524 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000525
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000526#ifdef Py_USING_UNICODE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000527 /* Cleanup Unicode implementation */
528 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000529#endif
530
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000531 /* XXX Still allocated:
532 - various static ad-hoc pointers to interned strings
533 - int and float free list blocks
534 - whatever various modules and libraries allocate
535 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000536
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000537 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000538
Tim Peters269b2a62003-04-17 19:52:29 +0000539#ifdef Py_TRACE_REFS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000540 /* Display addresses (& refcnts) of all objects still alive.
541 * An address can be used to find the repr of the object, printed
542 * above by _Py_PrintReferences.
543 */
544 if (Py_GETENV("PYTHONDUMPREFS"))
545 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000546#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000547#ifdef PYMALLOC_DEBUG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000548 if (Py_GETENV("PYTHONMALLOCSTATS"))
549 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000550#endif
551
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000552 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000553}
554
555/* Create and initialize a new interpreter and thread, and return the
556 new thread. This requires that Py_Initialize() has been called
557 first.
558
559 Unsuccessful initialization yields a NULL pointer. Note that *no*
560 exception information is available even in this case -- the
561 exception information is held in the thread, and there is no
562 thread.
563
564 Locking: as above.
565
566*/
567
568PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000569Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000571 PyInterpreterState *interp;
572 PyThreadState *tstate, *save_tstate;
573 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000575 if (!initialized)
576 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000578 interp = PyInterpreterState_New();
579 if (interp == NULL)
580 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000581
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000582 tstate = PyThreadState_New(interp);
583 if (tstate == NULL) {
584 PyInterpreterState_Delete(interp);
585 return NULL;
586 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000587
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000588 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000590 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000592 interp->modules = PyDict_New();
593 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000595 bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
596 if (bimod != NULL) {
597 interp->builtins = PyModule_GetDict(bimod);
598 if (interp->builtins == NULL)
599 goto handle_error;
600 Py_INCREF(interp->builtins);
601 }
602 sysmod = _PyImport_FindExtension("sys", "sys");
603 if (bimod != NULL && sysmod != NULL) {
604 interp->sysdict = PyModule_GetDict(sysmod);
605 if (interp->sysdict == NULL)
606 goto handle_error;
607 Py_INCREF(interp->sysdict);
608 PySys_SetPath(Py_GetPath());
609 PyDict_SetItemString(interp->sysdict, "modules",
610 interp->modules);
611 _PyImportHooks_Init();
612 initmain();
613 if (!Py_NoSiteFlag)
614 initsite();
615 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000616
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000617 if (!PyErr_Occurred())
618 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000619
Neal Norwitz0c6ae5b2006-08-21 20:16:24 +0000620handle_error:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000621 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000622
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000623 PyErr_Print();
624 PyThreadState_Clear(tstate);
625 PyThreadState_Swap(save_tstate);
626 PyThreadState_Delete(tstate);
627 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000628
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000629 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630}
631
632/* Delete an interpreter and its last thread. This requires that the
633 given thread state is current, that the thread has no remaining
634 frames, and that it is its interpreter's only remaining thread.
635 It is a fatal error to violate these constraints.
636
637 (Py_Finalize() doesn't have these constraints -- it zaps
638 everything, regardless.)
639
640 Locking: as above.
641
642*/
643
644void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000645Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000646{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000647 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000648
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000649 if (tstate != PyThreadState_GET())
650 Py_FatalError("Py_EndInterpreter: thread is not current");
651 if (tstate->frame != NULL)
652 Py_FatalError("Py_EndInterpreter: thread still has a frame");
653 if (tstate != interp->tstate_head || tstate->next != NULL)
654 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000655
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000656 PyImport_Cleanup();
657 PyInterpreterState_Clear(interp);
658 PyThreadState_Swap(NULL);
659 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000660}
661
662static char *progname = "python";
663
664void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000665Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000666{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000667 if (pn && *pn)
668 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000669}
670
671char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000672Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000673{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000674 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000675}
676
Guido van Rossuma61691e1998-02-06 22:27:24 +0000677static char *default_home = NULL;
678
679void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000680Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000681{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000682 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000683}
684
685char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000686Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000687{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000688 char *home = default_home;
689 if (home == NULL && !Py_IgnoreEnvironmentFlag)
690 home = Py_GETENV("PYTHONHOME");
691 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000692}
693
Guido van Rossum6135a871995-01-09 17:53:26 +0000694/* Create __main__ module */
695
696static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000697initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000698{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000699 PyObject *m, *d;
700 m = PyImport_AddModule("__main__");
701 if (m == NULL)
702 Py_FatalError("can't create __main__ module");
703 d = PyModule_GetDict(m);
704 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
705 PyObject *bimod = PyImport_ImportModule("__builtin__");
706 if (bimod == NULL ||
707 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
708 Py_FatalError("can't add __builtins__ to __main__");
709 Py_DECREF(bimod);
710 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000711}
712
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000713/* Import the site module (not into __main__ though) */
714
715static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000716initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000717{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000718 PyObject *m, *f;
719 m = PyImport_ImportModule("site");
720 if (m == NULL) {
721 f = PySys_GetObject("stderr");
722 if (Py_VerboseFlag) {
723 PyFile_WriteString(
724 "'import site' failed; traceback:\n", f);
725 PyErr_Print();
726 }
727 else {
728 PyFile_WriteString(
729 "'import site' failed; use -v for traceback\n", f);
730 PyErr_Clear();
731 }
732 }
733 else {
734 Py_DECREF(m);
735 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000736}
737
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000738/* Parse input from a file and execute it */
739
740int
Tim Peters5e9d6cf2006-05-28 10:41:29 +0000741PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000742 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000743{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000744 if (filename == NULL)
745 filename = "???";
746 if (Py_FdIsInteractive(fp, filename)) {
747 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
748 if (closeit)
749 fclose(fp);
750 return err;
751 }
752 else
753 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000754}
755
756int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000757PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000758{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000759 PyObject *v;
760 int ret;
761 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000762
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000763 if (flags == NULL) {
764 flags = &local_flags;
765 local_flags.cf_flags = 0;
766 }
767 v = PySys_GetObject("ps1");
768 if (v == NULL) {
769 PySys_SetObject("ps1", v = PyString_FromString(">>> "));
770 Py_XDECREF(v);
771 }
772 v = PySys_GetObject("ps2");
773 if (v == NULL) {
774 PySys_SetObject("ps2", v = PyString_FromString("... "));
775 Py_XDECREF(v);
776 }
777 for (;;) {
778 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
779 PRINT_TOTAL_REFS();
780 if (ret == E_EOF)
781 return 0;
782 /*
783 if (ret == E_NOMEM)
784 return -1;
785 */
786 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000787}
788
Eric Smith7c478942008-03-18 23:45:49 +0000789#if 0
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000790/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000791#define PARSER_FLAGS(flags) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000792 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
793 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Eric Smith7c478942008-03-18 23:45:49 +0000794#endif
795#if 1
Neal Norwitzca460d92006-09-06 06:28:06 +0000796/* Keep an example of flags with future keyword support. */
797#define PARSER_FLAGS(flags) \
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000798 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
799 PyPARSE_DONT_IMPLY_DEDENT : 0) \
800 | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
801 PyPARSE_PRINT_IS_FUNCTION : 0) \
802 | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
803 PyPARSE_UNICODE_LITERALS : 0) \
804 ) : 0)
Neal Norwitzca460d92006-09-06 06:28:06 +0000805#endif
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000806
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000807int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000808PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000809{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000810 PyObject *m, *d, *v, *w;
811 mod_ty mod;
812 PyArena *arena;
813 char *ps1 = "", *ps2 = "";
814 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000815
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000816 v = PySys_GetObject("ps1");
817 if (v != NULL) {
818 v = PyObject_Str(v);
819 if (v == NULL)
820 PyErr_Clear();
821 else if (PyString_Check(v))
822 ps1 = PyString_AsString(v);
823 }
824 w = PySys_GetObject("ps2");
825 if (w != NULL) {
826 w = PyObject_Str(w);
827 if (w == NULL)
828 PyErr_Clear();
829 else if (PyString_Check(w))
830 ps2 = PyString_AsString(w);
831 }
832 arena = PyArena_New();
833 if (arena == NULL) {
834 Py_XDECREF(v);
835 Py_XDECREF(w);
836 return -1;
837 }
838 mod = PyParser_ASTFromFile(fp, filename,
839 Py_single_input, ps1, ps2,
840 flags, &errcode, arena);
841 Py_XDECREF(v);
842 Py_XDECREF(w);
843 if (mod == NULL) {
844 PyArena_Free(arena);
845 if (errcode == E_EOF) {
846 PyErr_Clear();
847 return E_EOF;
848 }
849 PyErr_Print();
850 return -1;
851 }
852 m = PyImport_AddModule("__main__");
853 if (m == NULL) {
854 PyArena_Free(arena);
855 return -1;
856 }
857 d = PyModule_GetDict(m);
858 v = run_mod(mod, filename, d, d, flags, arena);
859 PyArena_Free(arena);
860 if (v == NULL) {
861 PyErr_Print();
862 return -1;
863 }
864 Py_DECREF(v);
865 if (Py_FlushLine())
866 PyErr_Clear();
867 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000868}
869
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000870/* Check whether a file maybe a pyc file: Look at the extension,
871 the file type, and, if we may close it, at the first few bytes. */
872
873static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000874maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000875{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000876 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
877 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000878
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000879 /* Only look into the file if we are allowed to close it, since
880 it then should also be seekable. */
881 if (closeit) {
882 /* Read only two bytes of the magic. If the file was opened in
883 text mode, the bytes 3 and 4 of the magic (\r\n) might not
884 be read as they are on disk. */
885 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
886 unsigned char buf[2];
887 /* Mess: In case of -x, the stream is NOT at its start now,
888 and ungetc() was used to push back the first newline,
889 which makes the current stream position formally undefined,
890 and a x-platform nightmare.
891 Unfortunately, we have no direct way to know whether -x
892 was specified. So we use a terrible hack: if the current
893 stream position is not 0, we assume -x was specified, and
894 give up. Bug 132850 on SourceForge spells out the
895 hopelessness of trying anything else (fseek and ftell
896 don't work predictably x-platform for text-mode files).
897 */
898 int ispyc = 0;
899 if (ftell(fp) == 0) {
900 if (fread(buf, 1, 2, fp) == 2 &&
901 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
902 ispyc = 1;
903 rewind(fp);
904 }
905 return ispyc;
906 }
907 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +0000908}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000909
Guido van Rossum0df002c2000-08-27 19:21:52 +0000910int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000911PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000912 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000913{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000914 PyObject *m, *d, *v;
915 const char *ext;
916 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +0000917
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000918 m = PyImport_AddModule("__main__");
919 if (m == NULL)
920 return -1;
921 d = PyModule_GetDict(m);
922 if (PyDict_GetItemString(d, "__file__") == NULL) {
923 PyObject *f = PyString_FromString(filename);
924 if (f == NULL)
925 return -1;
926 if (PyDict_SetItemString(d, "__file__", f) < 0) {
927 Py_DECREF(f);
928 return -1;
929 }
930 set_file_name = 1;
931 Py_DECREF(f);
932 }
933 len = strlen(filename);
934 ext = filename + len - (len > 4 ? 4 : 0);
935 if (maybe_pyc_file(fp, filename, ext, closeit)) {
936 /* Try to run a pyc file. First, re-open in binary */
937 if (closeit)
938 fclose(fp);
939 if ((fp = fopen(filename, "rb")) == NULL) {
940 fprintf(stderr, "python: Can't reopen .pyc file\n");
941 ret = -1;
942 goto done;
943 }
944 /* Turn on optimization if a .pyo file is given */
945 if (strcmp(ext, ".pyo") == 0)
946 Py_OptimizeFlag = 1;
947 v = run_pyc_file(fp, filename, d, d, flags);
948 } else {
949 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
950 closeit, flags);
951 }
952 if (v == NULL) {
953 PyErr_Print();
954 ret = -1;
955 goto done;
956 }
957 Py_DECREF(v);
958 if (Py_FlushLine())
959 PyErr_Clear();
960 ret = 0;
Georg Brandlaa2321b2007-03-07 00:40:28 +0000961 done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000962 if (set_file_name && PyDict_DelItemString(d, "__file__"))
963 PyErr_Clear();
964 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000965}
966
967int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000968PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +0000969{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000970 PyObject *m, *d, *v;
971 m = PyImport_AddModule("__main__");
972 if (m == NULL)
973 return -1;
974 d = PyModule_GetDict(m);
975 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
976 if (v == NULL) {
977 PyErr_Print();
978 return -1;
979 }
980 Py_DECREF(v);
981 if (Py_FlushLine())
982 PyErr_Clear();
983 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000984}
985
Barry Warsaw035574d1997-08-29 22:07:17 +0000986static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000987parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000988 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +0000989{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000990 long hold;
991 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +0000992
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000993 /* old style errors */
994 if (PyTuple_Check(err))
995 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
996 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +0000997
Antoine Pitrouc7c96a92010-05-09 15:15:40 +0000998 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +0000999
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001000 if (! (v = PyObject_GetAttrString(err, "msg")))
1001 goto finally;
1002 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001003
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001004 if (!(v = PyObject_GetAttrString(err, "filename")))
1005 goto finally;
1006 if (v == Py_None)
1007 *filename = NULL;
1008 else if (! (*filename = PyString_AsString(v)))
1009 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001010
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001011 Py_DECREF(v);
1012 if (!(v = PyObject_GetAttrString(err, "lineno")))
1013 goto finally;
1014 hold = PyInt_AsLong(v);
1015 Py_DECREF(v);
1016 v = NULL;
1017 if (hold < 0 && PyErr_Occurred())
1018 goto finally;
1019 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001020
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001021 if (!(v = PyObject_GetAttrString(err, "offset")))
1022 goto finally;
1023 if (v == Py_None) {
1024 *offset = -1;
1025 Py_DECREF(v);
1026 v = NULL;
1027 } else {
1028 hold = PyInt_AsLong(v);
1029 Py_DECREF(v);
1030 v = NULL;
1031 if (hold < 0 && PyErr_Occurred())
1032 goto finally;
1033 *offset = (int)hold;
1034 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001035
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001036 if (!(v = PyObject_GetAttrString(err, "text")))
1037 goto finally;
1038 if (v == Py_None)
1039 *text = NULL;
1040 else if (! (*text = PyString_AsString(v)))
1041 goto finally;
1042 Py_DECREF(v);
1043 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001044
1045finally:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001046 Py_XDECREF(v);
1047 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001048}
1049
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001050void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001051PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001052{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001053 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001054}
1055
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001056static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001057print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001058{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001059 char *nl;
1060 if (offset >= 0) {
1061 if (offset > 0 && offset == (int)strlen(text))
1062 offset--;
1063 for (;;) {
1064 nl = strchr(text, '\n');
1065 if (nl == NULL || nl-text >= offset)
1066 break;
1067 offset -= (int)(nl+1-text);
1068 text = nl+1;
1069 }
1070 while (*text == ' ' || *text == '\t') {
1071 text++;
1072 offset--;
1073 }
1074 }
1075 PyFile_WriteString(" ", f);
1076 PyFile_WriteString(text, f);
1077 if (*text == '\0' || text[strlen(text)-1] != '\n')
1078 PyFile_WriteString("\n", f);
1079 if (offset == -1)
1080 return;
1081 PyFile_WriteString(" ", f);
1082 offset--;
1083 while (offset > 0) {
1084 PyFile_WriteString(" ", f);
1085 offset--;
1086 }
1087 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001088}
1089
Guido van Rossum66e8e862001-03-23 17:54:43 +00001090static void
1091handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001092{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001093 PyObject *exception, *value, *tb;
1094 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001095
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001096 if (Py_InspectFlag)
1097 /* Don't exit if -i flag was given. This flag is set to 0
1098 * when entering interactive mode for inspecting. */
1099 return;
Georg Brandl49aafc92007-03-07 00:34:46 +00001100
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001101 PyErr_Fetch(&exception, &value, &tb);
1102 if (Py_FlushLine())
1103 PyErr_Clear();
1104 fflush(stdout);
1105 if (value == NULL || value == Py_None)
1106 goto done;
1107 if (PyExceptionInstance_Check(value)) {
1108 /* The error code should be in the `code' attribute. */
1109 PyObject *code = PyObject_GetAttrString(value, "code");
1110 if (code) {
1111 Py_DECREF(value);
1112 value = code;
1113 if (value == Py_None)
1114 goto done;
1115 }
1116 /* If we failed to dig out the 'code' attribute,
1117 just let the else clause below print the error. */
1118 }
1119 if (PyInt_Check(value))
1120 exitcode = (int)PyInt_AsLong(value);
1121 else {
Victor Stinnerc3e40e02010-05-25 22:40:38 +00001122 PyObject *sys_stderr = PySys_GetObject("stderr");
1123 if (sys_stderr != NULL && sys_stderr != Py_None) {
1124 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1125 } else {
1126 PyObject_Print(value, stderr, Py_PRINT_RAW);
1127 fflush(stderr);
1128 }
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001129 PySys_WriteStderr("\n");
1130 exitcode = 1;
1131 }
Tim Peterscf615b52003-04-19 18:47:02 +00001132 done:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001133 /* Restore and clear the exception info, in order to properly decref
1134 * the exception, value, and traceback. If we just exit instead,
1135 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1136 * some finalizers from running.
1137 */
1138 PyErr_Restore(exception, value, tb);
1139 PyErr_Clear();
1140 Py_Exit(exitcode);
1141 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001142}
1143
1144void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001145PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001146{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001147 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001148
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001149 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1150 handle_system_exit();
1151 }
1152 PyErr_Fetch(&exception, &v, &tb);
1153 if (exception == NULL)
1154 return;
1155 PyErr_NormalizeException(&exception, &v, &tb);
1156 if (exception == NULL)
1157 return;
1158 /* Now we know v != NULL too */
1159 if (set_sys_last_vars) {
1160 PySys_SetObject("last_type", exception);
1161 PySys_SetObject("last_value", v);
1162 PySys_SetObject("last_traceback", tb);
1163 }
1164 hook = PySys_GetObject("excepthook");
1165 if (hook) {
1166 PyObject *args = PyTuple_Pack(3,
1167 exception, v, tb ? tb : Py_None);
1168 PyObject *result = PyEval_CallObject(hook, args);
1169 if (result == NULL) {
1170 PyObject *exception2, *v2, *tb2;
1171 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1172 handle_system_exit();
1173 }
1174 PyErr_Fetch(&exception2, &v2, &tb2);
1175 PyErr_NormalizeException(&exception2, &v2, &tb2);
1176 /* It should not be possible for exception2 or v2
1177 to be NULL. However PyErr_Display() can't
1178 tolerate NULLs, so just be safe. */
1179 if (exception2 == NULL) {
1180 exception2 = Py_None;
1181 Py_INCREF(exception2);
1182 }
1183 if (v2 == NULL) {
1184 v2 = Py_None;
1185 Py_INCREF(v2);
1186 }
1187 if (Py_FlushLine())
1188 PyErr_Clear();
1189 fflush(stdout);
1190 PySys_WriteStderr("Error in sys.excepthook:\n");
1191 PyErr_Display(exception2, v2, tb2);
1192 PySys_WriteStderr("\nOriginal exception was:\n");
1193 PyErr_Display(exception, v, tb);
1194 Py_DECREF(exception2);
1195 Py_DECREF(v2);
1196 Py_XDECREF(tb2);
1197 }
1198 Py_XDECREF(result);
1199 Py_XDECREF(args);
1200 } else {
1201 PySys_WriteStderr("sys.excepthook is missing\n");
1202 PyErr_Display(exception, v, tb);
1203 }
1204 Py_XDECREF(exception);
1205 Py_XDECREF(v);
1206 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001207}
1208
Richard Jones7b9558d2006-05-27 12:29:24 +00001209void
1210PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001211{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001212 int err = 0;
1213 PyObject *f = PySys_GetObject("stderr");
1214 Py_INCREF(value);
1215 if (f == NULL)
1216 fprintf(stderr, "lost sys.stderr\n");
1217 else {
1218 if (Py_FlushLine())
1219 PyErr_Clear();
1220 fflush(stdout);
1221 if (tb && tb != Py_None)
1222 err = PyTraceBack_Print(tb, f);
1223 if (err == 0 &&
1224 PyObject_HasAttrString(value, "print_file_and_line"))
1225 {
1226 PyObject *message;
1227 const char *filename, *text;
1228 int lineno, offset;
1229 if (!parse_syntax_error(value, &message, &filename,
1230 &lineno, &offset, &text))
1231 PyErr_Clear();
1232 else {
1233 char buf[10];
1234 PyFile_WriteString(" File \"", f);
1235 if (filename == NULL)
1236 PyFile_WriteString("<string>", f);
1237 else
1238 PyFile_WriteString(filename, f);
1239 PyFile_WriteString("\", line ", f);
1240 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1241 PyFile_WriteString(buf, f);
1242 PyFile_WriteString("\n", f);
1243 if (text != NULL)
1244 print_error_text(f, offset, text);
1245 Py_DECREF(value);
1246 value = message;
1247 /* Can't be bothered to check all those
1248 PyFile_WriteString() calls */
1249 if (PyErr_Occurred())
1250 err = -1;
1251 }
1252 }
1253 if (err) {
1254 /* Don't do anything else */
1255 }
1256 else if (PyExceptionClass_Check(exception)) {
1257 PyObject* moduleName;
1258 char* className = PyExceptionClass_Name(exception);
1259 if (className != NULL) {
1260 char *dot = strrchr(className, '.');
1261 if (dot != NULL)
1262 className = dot+1;
1263 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001264
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001265 moduleName = PyObject_GetAttrString(exception, "__module__");
1266 if (moduleName == NULL)
1267 err = PyFile_WriteString("<unknown>", f);
1268 else {
1269 char* modstr = PyString_AsString(moduleName);
1270 if (modstr && strcmp(modstr, "exceptions"))
1271 {
1272 err = PyFile_WriteString(modstr, f);
1273 err += PyFile_WriteString(".", f);
1274 }
1275 Py_DECREF(moduleName);
1276 }
1277 if (err == 0) {
1278 if (className == NULL)
1279 err = PyFile_WriteString("<unknown>", f);
1280 else
1281 err = PyFile_WriteString(className, f);
1282 }
1283 }
1284 else
1285 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
1286 if (err == 0 && (value != Py_None)) {
1287 PyObject *s = PyObject_Str(value);
1288 /* only print colon if the str() of the
1289 object is not the empty string
1290 */
1291 if (s == NULL)
1292 err = -1;
1293 else if (!PyString_Check(s) ||
1294 PyString_GET_SIZE(s) != 0)
1295 err = PyFile_WriteString(": ", f);
1296 if (err == 0)
1297 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1298 Py_XDECREF(s);
1299 }
1300 /* try to write a newline in any case */
1301 err += PyFile_WriteString("\n", f);
1302 }
1303 Py_DECREF(value);
1304 /* If an error happened here, don't show it.
1305 XXX This is wrong, but too many callers rely on this behavior. */
1306 if (err != 0)
1307 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001308}
1309
Guido van Rossum82598051997-03-05 00:20:32 +00001310PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001311PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001312 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001313{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001314 PyObject *ret = NULL;
1315 mod_ty mod;
1316 PyArena *arena = PyArena_New();
1317 if (arena == NULL)
1318 return NULL;
1319
1320 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1321 if (mod != NULL)
1322 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1323 PyArena_Free(arena);
1324 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001325}
1326
1327PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001328PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001329 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001330{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001331 PyObject *ret;
1332 mod_ty mod;
1333 PyArena *arena = PyArena_New();
1334 if (arena == NULL)
1335 return NULL;
1336
1337 mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
1338 flags, NULL, arena);
1339 if (closeit)
1340 fclose(fp);
1341 if (mod == NULL) {
1342 PyArena_Free(arena);
1343 return NULL;
1344 }
1345 ret = run_mod(mod, filename, globals, locals, flags, arena);
1346 PyArena_Free(arena);
1347 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001348}
1349
Guido van Rossum82598051997-03-05 00:20:32 +00001350static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001351run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001352 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001353{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001354 PyCodeObject *co;
1355 PyObject *v;
1356 co = PyAST_Compile(mod, filename, flags, arena);
1357 if (co == NULL)
1358 return NULL;
1359 v = PyEval_EvalCode(co, globals, locals);
1360 Py_DECREF(co);
1361 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001362}
1363
Guido van Rossum82598051997-03-05 00:20:32 +00001364static PyObject *
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001365run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001366 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001367{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001368 PyCodeObject *co;
1369 PyObject *v;
1370 long magic;
1371 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001372
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001373 magic = PyMarshal_ReadLongFromFile(fp);
1374 if (magic != PyImport_GetMagicNumber()) {
1375 PyErr_SetString(PyExc_RuntimeError,
1376 "Bad magic number in .pyc file");
1377 return NULL;
1378 }
1379 (void) PyMarshal_ReadLongFromFile(fp);
1380 v = PyMarshal_ReadLastObjectFromFile(fp);
1381 fclose(fp);
1382 if (v == NULL || !PyCode_Check(v)) {
1383 Py_XDECREF(v);
1384 PyErr_SetString(PyExc_RuntimeError,
1385 "Bad code object in .pyc file");
1386 return NULL;
1387 }
1388 co = (PyCodeObject *)v;
1389 v = PyEval_EvalCode(co, globals, locals);
1390 if (v && flags)
1391 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1392 Py_DECREF(co);
1393 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001394}
1395
Guido van Rossum82598051997-03-05 00:20:32 +00001396PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001397Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001398 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001399{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001400 PyCodeObject *co;
1401 mod_ty mod;
1402 PyArena *arena = PyArena_New();
1403 if (arena == NULL)
1404 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001405
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001406 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1407 if (mod == NULL) {
1408 PyArena_Free(arena);
1409 return NULL;
1410 }
1411 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1412 PyObject *result = PyAST_mod2obj(mod);
1413 PyArena_Free(arena);
1414 return result;
1415 }
1416 co = PyAST_Compile(mod, filename, flags, arena);
1417 PyArena_Free(arena);
1418 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001419}
1420
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001421struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001422Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001423{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001424 struct symtable *st;
1425 mod_ty mod;
1426 PyCompilerFlags flags;
1427 PyArena *arena = PyArena_New();
1428 if (arena == NULL)
1429 return NULL;
Neal Norwitzb59d08c2006-07-22 16:20:49 +00001430
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001431 flags.cf_flags = 0;
Christian Heimes7f23d862008-03-26 22:51:58 +00001432
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001433 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1434 if (mod == NULL) {
1435 PyArena_Free(arena);
1436 return NULL;
1437 }
1438 st = PySymtable_Build(mod, filename, 0);
1439 PyArena_Free(arena);
1440 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001441}
1442
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001443/* Preferred access to parser is through AST. */
1444mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001445PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001446 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001448 mod_ty mod;
1449 PyCompilerFlags localflags;
1450 perrdetail err;
1451 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001452
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001453 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1454 &_PyParser_Grammar, start, &err,
1455 &iflags);
1456 if (flags == NULL) {
1457 localflags.cf_flags = 0;
1458 flags = &localflags;
1459 }
1460 if (n) {
1461 flags->cf_flags |= iflags & PyCF_MASK;
1462 mod = PyAST_FromNode(n, flags, filename, arena);
1463 PyNode_Free(n);
1464 return mod;
1465 }
1466 else {
1467 err_input(&err);
1468 return NULL;
1469 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001470}
1471
1472mod_ty
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001473PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001474 char *ps2, PyCompilerFlags *flags, int *errcode,
1475 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001477 mod_ty mod;
1478 PyCompilerFlags localflags;
1479 perrdetail err;
1480 int iflags = PARSER_FLAGS(flags);
Christian Heimes3c608332008-03-26 22:01:37 +00001481
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001482 node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
1483 start, ps1, ps2, &err, &iflags);
1484 if (flags == NULL) {
1485 localflags.cf_flags = 0;
1486 flags = &localflags;
1487 }
1488 if (n) {
1489 flags->cf_flags |= iflags & PyCF_MASK;
1490 mod = PyAST_FromNode(n, flags, filename, arena);
1491 PyNode_Free(n);
1492 return mod;
1493 }
1494 else {
1495 err_input(&err);
1496 if (errcode)
1497 *errcode = err.error;
1498 return NULL;
1499 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001500}
1501
Guido van Rossuma110aa61994-08-29 12:50:44 +00001502/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001503
Guido van Rossuma110aa61994-08-29 12:50:44 +00001504node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001505PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001506{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001507 perrdetail err;
1508 node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
1509 start, NULL, NULL, &err, flags);
1510 if (n == NULL)
1511 err_input(&err);
Tim Peters5e9d6cf2006-05-28 10:41:29 +00001512
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001513 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001514}
1515
Guido van Rossuma110aa61994-08-29 12:50:44 +00001516/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001517
Guido van Rossuma110aa61994-08-29 12:50:44 +00001518node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001519PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001520{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001521 perrdetail err;
1522 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1523 start, &err, flags);
1524 if (n == NULL)
1525 err_input(&err);
1526 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001527}
1528
1529node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001530PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001531 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001532{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001533 perrdetail err;
1534 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1535 &_PyParser_Grammar, start, &err, flags);
1536 if (n == NULL)
1537 err_input(&err);
1538 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001539}
1540
1541node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001542PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001543{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001544 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001545}
1546
Guido van Rossum66ebd912003-04-17 16:02:26 +00001547/* May want to move a more generalized form of this to parsetok.c or
1548 even parser modules. */
1549
1550void
1551PyParser_SetError(perrdetail *err)
1552{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001553 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001554}
1555
Guido van Rossuma110aa61994-08-29 12:50:44 +00001556/* Set the error appropriate to the given input error code (see errcode.h) */
1557
1558static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001559err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001560{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001561 PyObject *v, *w, *errtype;
1562 PyObject* u = NULL;
1563 char *msg = NULL;
1564 errtype = PyExc_SyntaxError;
1565 switch (err->error) {
1566 case E_ERROR:
1567 return;
1568 case E_SYNTAX:
1569 errtype = PyExc_IndentationError;
1570 if (err->expected == INDENT)
1571 msg = "expected an indented block";
1572 else if (err->token == INDENT)
1573 msg = "unexpected indent";
1574 else if (err->token == DEDENT)
1575 msg = "unexpected unindent";
1576 else {
1577 errtype = PyExc_SyntaxError;
1578 msg = "invalid syntax";
1579 }
1580 break;
1581 case E_TOKEN:
1582 msg = "invalid token";
1583 break;
1584 case E_EOFS:
1585 msg = "EOF while scanning triple-quoted string literal";
1586 break;
1587 case E_EOLS:
1588 msg = "EOL while scanning string literal";
1589 break;
1590 case E_INTR:
1591 if (!PyErr_Occurred())
1592 PyErr_SetNone(PyExc_KeyboardInterrupt);
1593 goto cleanup;
1594 case E_NOMEM:
1595 PyErr_NoMemory();
1596 goto cleanup;
1597 case E_EOF:
1598 msg = "unexpected EOF while parsing";
1599 break;
1600 case E_TABSPACE:
1601 errtype = PyExc_TabError;
1602 msg = "inconsistent use of tabs and spaces in indentation";
1603 break;
1604 case E_OVERFLOW:
1605 msg = "expression too long";
1606 break;
1607 case E_DEDENT:
1608 errtype = PyExc_IndentationError;
1609 msg = "unindent does not match any outer indentation level";
1610 break;
1611 case E_TOODEEP:
1612 errtype = PyExc_IndentationError;
1613 msg = "too many levels of indentation";
1614 break;
1615 case E_DECODE: {
1616 PyObject *type, *value, *tb;
1617 PyErr_Fetch(&type, &value, &tb);
1618 if (value != NULL) {
1619 u = PyObject_Str(value);
1620 if (u != NULL) {
1621 msg = PyString_AsString(u);
1622 }
1623 }
1624 if (msg == NULL)
1625 msg = "unknown decode error";
1626 Py_XDECREF(type);
1627 Py_XDECREF(value);
1628 Py_XDECREF(tb);
1629 break;
1630 }
1631 case E_LINECONT:
1632 msg = "unexpected character after line continuation character";
1633 break;
1634 default:
1635 fprintf(stderr, "error=%d\n", err->error);
1636 msg = "unknown parsing error";
1637 break;
1638 }
1639 v = Py_BuildValue("(ziiz)", err->filename,
1640 err->lineno, err->offset, err->text);
1641 w = NULL;
1642 if (v != NULL)
1643 w = Py_BuildValue("(sO)", msg, v);
1644 Py_XDECREF(u);
1645 Py_XDECREF(v);
1646 PyErr_SetObject(errtype, w);
1647 Py_XDECREF(w);
Georg Brandl1ad108d2008-07-19 10:08:55 +00001648cleanup:
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001649 if (err->text != NULL) {
1650 PyObject_FREE(err->text);
1651 err->text = NULL;
1652 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001653}
1654
1655/* Print fatal error message and abort */
1656
1657void
Tim Peters7c321a82002-07-09 02:57:01 +00001658Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001659{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001660 fprintf(stderr, "Fatal Python error: %s\n", msg);
1661 fflush(stderr); /* it helps in Windows debug build */
Jesse Noller70b11f02009-03-31 22:25:20 +00001662
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001663#ifdef MS_WINDOWS
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001664 {
1665 size_t len = strlen(msg);
1666 WCHAR* buffer;
1667 size_t i;
Georg Brandl734373c2009-01-03 21:55:17 +00001668
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001669 /* Convert the message to wchar_t. This uses a simple one-to-one
1670 conversion, assuming that the this error message actually uses ASCII
1671 only. If this ceases to be true, we will have to convert. */
1672 buffer = alloca( (len+1) * (sizeof *buffer));
1673 for( i=0; i<=len; ++i)
1674 buffer[i] = msg[i];
1675 OutputDebugStringW(L"Fatal Python error: ");
1676 OutputDebugStringW(buffer);
1677 OutputDebugStringW(L"\n");
1678 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001679#ifdef _DEBUG
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001680 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001681#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001682#endif /* MS_WINDOWS */
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001683 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001684}
1685
1686/* Clean up and exit */
1687
Guido van Rossuma110aa61994-08-29 12:50:44 +00001688#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001689#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001690#endif
1691
Antoine Pitrou9aece752009-10-27 12:48:52 +00001692/* Wait until threading._shutdown completes, provided
1693 the threading module was imported in the first place.
1694 The shutdown routine will wait until all non-daemon
1695 "threading" threads have completed. */
1696static void
1697wait_for_thread_shutdown(void)
1698{
1699#ifdef WITH_THREAD
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001700 PyObject *result;
1701 PyThreadState *tstate = PyThreadState_GET();
1702 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1703 "threading");
1704 if (threading == NULL) {
1705 /* threading not imported */
1706 PyErr_Clear();
1707 return;
1708 }
1709 result = PyObject_CallMethod(threading, "_shutdown", "");
1710 if (result == NULL)
1711 PyErr_WriteUnraisable(threading);
1712 else
1713 Py_DECREF(result);
1714 Py_DECREF(threading);
Antoine Pitrou9aece752009-10-27 12:48:52 +00001715#endif
1716}
1717
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001718#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001719static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001720static int nexitfuncs = 0;
1721
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001722int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001723{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001724 if (nexitfuncs >= NEXITFUNCS)
1725 return -1;
1726 exitfuncs[nexitfuncs++] = func;
1727 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00001728}
1729
Guido van Rossumcc283f51997-08-05 02:22:03 +00001730static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001731call_sys_exitfunc(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001732{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001733 PyObject *exitfunc = PySys_GetObject("exitfunc");
Guido van Rossum59bff391992-09-03 20:28:00 +00001734
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001735 if (exitfunc) {
1736 PyObject *res;
1737 Py_INCREF(exitfunc);
1738 PySys_SetObject("exitfunc", (PyObject *)NULL);
1739 res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
1740 if (res == NULL) {
1741 if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
1742 PySys_WriteStderr("Error in sys.exitfunc:\n");
1743 }
1744 PyErr_Print();
1745 }
1746 Py_DECREF(exitfunc);
1747 }
Guido van Rossum59bff391992-09-03 20:28:00 +00001748
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001749 if (Py_FlushLine())
1750 PyErr_Clear();
Guido van Rossumcc283f51997-08-05 02:22:03 +00001751}
Guido van Rossum1662dd51994-09-07 14:38:28 +00001752
Guido van Rossumcc283f51997-08-05 02:22:03 +00001753static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001754call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001755{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001756 while (nexitfuncs > 0)
1757 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001758
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001759 fflush(stdout);
1760 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001761}
1762
1763void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001764Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001765{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001766 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001767
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001768 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001769}
1770
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001771static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001772initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001773{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001774#ifdef SIGPIPE
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001775 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001776#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001777#ifdef SIGXFZ
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001778 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001779#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001780#ifdef SIGXFSZ
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001781 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001782#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001783 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001784}
1785
Guido van Rossum7433b121997-02-14 19:45:36 +00001786
1787/*
1788 * The file descriptor fd is considered ``interactive'' if either
1789 * a) isatty(fd) is TRUE, or
1790 * b) the -i flag was given, and the filename associated with
1791 * the descriptor is NULL or "<stdin>" or "???".
1792 */
1793int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001794Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001795{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001796 if (isatty((int)fileno(fp)))
1797 return 1;
1798 if (!Py_InteractiveFlag)
1799 return 0;
1800 return (filename == NULL) ||
1801 (strcmp(filename, "<stdin>") == 0) ||
1802 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00001803}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001804
1805
Tim Petersd08e3822003-04-17 15:24:21 +00001806#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001807#if defined(WIN32) && defined(_MSC_VER)
1808
1809/* Stack checking for Microsoft C */
1810
1811#include <malloc.h>
1812#include <excpt.h>
1813
Fred Drakee8de31c2000-08-31 05:38:39 +00001814/*
1815 * Return non-zero when we run out of memory on the stack; zero otherwise.
1816 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001817int
Fred Drake399739f2000-08-31 05:52:44 +00001818PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001819{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001820 __try {
1821 /* alloca throws a stack overflow exception if there's
1822 not enough space left on the stack */
1823 alloca(PYOS_STACK_MARGIN * sizeof(void*));
1824 return 0;
1825 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
1826 EXCEPTION_EXECUTE_HANDLER :
1827 EXCEPTION_CONTINUE_SEARCH) {
1828 int errcode = _resetstkoflw();
1829 if (errcode == 0)
1830 {
1831 Py_FatalError("Could not reset the stack!");
1832 }
1833 }
1834 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001835}
1836
1837#endif /* WIN32 && _MSC_VER */
1838
1839/* Alternate implementations can be added here... */
1840
1841#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001842
1843
1844/* Wrappers around sigaction() or signal(). */
1845
1846PyOS_sighandler_t
1847PyOS_getsig(int sig)
1848{
1849#ifdef HAVE_SIGACTION
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001850 struct sigaction context;
1851 if (sigaction(sig, NULL, &context) == -1)
1852 return SIG_ERR;
1853 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001854#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001855 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001856/* Special signal handling for the secure CRT in Visual Studio 2005 */
1857#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001858 switch (sig) {
1859 /* Only these signals are valid */
1860 case SIGINT:
1861 case SIGILL:
1862 case SIGFPE:
1863 case SIGSEGV:
1864 case SIGTERM:
1865 case SIGBREAK:
1866 case SIGABRT:
1867 break;
1868 /* Don't call signal() with other values or it will assert */
1869 default:
1870 return SIG_ERR;
1871 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001872#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001873 handler = signal(sig, SIG_IGN);
1874 if (handler != SIG_ERR)
1875 signal(sig, handler);
1876 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001877#endif
1878}
1879
1880PyOS_sighandler_t
1881PyOS_setsig(int sig, PyOS_sighandler_t handler)
1882{
1883#ifdef HAVE_SIGACTION
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001884 /* Some code in Modules/signalmodule.c depends on sigaction() being
1885 * used here if HAVE_SIGACTION is defined. Fix that if this code
1886 * changes to invalidate that assumption.
1887 */
1888 struct sigaction context, ocontext;
1889 context.sa_handler = handler;
1890 sigemptyset(&context.sa_mask);
1891 context.sa_flags = 0;
1892 if (sigaction(sig, &context, &ocontext) == -1)
1893 return SIG_ERR;
1894 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001895#else
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001896 PyOS_sighandler_t oldhandler;
1897 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001898#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001899 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001900#endif
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001901 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00001902#endif
1903}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001904
1905/* Deprecated C API functions still provided for binary compatiblity */
1906
1907#undef PyParser_SimpleParseFile
Thomas Heller1b046642006-04-18 18:51:06 +00001908PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001909PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
1910{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001911 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001912}
1913
Thomas Heller1b046642006-04-18 18:51:06 +00001914#undef PyParser_SimpleParseString
1915PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001916PyParser_SimpleParseString(const char *str, int start)
1917{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001918 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919}
Anthony Baxterac6bd462006-04-13 02:06:09 +00001920
Thomas Heller1b046642006-04-18 18:51:06 +00001921#undef PyRun_AnyFile
1922PyAPI_FUNC(int)
1923PyRun_AnyFile(FILE *fp, const char *name)
1924{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001925 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001926}
1927
1928#undef PyRun_AnyFileEx
1929PyAPI_FUNC(int)
1930PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
1931{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001932 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001933}
1934
1935#undef PyRun_AnyFileFlags
1936PyAPI_FUNC(int)
1937PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
1938{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001939 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001940}
1941
1942#undef PyRun_File
1943PyAPI_FUNC(PyObject *)
1944PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
1945{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001946 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001947}
1948
1949#undef PyRun_FileEx
1950PyAPI_FUNC(PyObject *)
1951PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
1952{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001953 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001954}
1955
1956#undef PyRun_FileFlags
1957PyAPI_FUNC(PyObject *)
1958PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001959 PyCompilerFlags *flags)
Thomas Heller1b046642006-04-18 18:51:06 +00001960{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001961 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Heller1b046642006-04-18 18:51:06 +00001962}
1963
1964#undef PyRun_SimpleFile
1965PyAPI_FUNC(int)
1966PyRun_SimpleFile(FILE *f, const char *p)
1967{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001968 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001969}
1970
1971#undef PyRun_SimpleFileEx
1972PyAPI_FUNC(int)
1973PyRun_SimpleFileEx(FILE *f, const char *p, int c)
1974{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001975 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001976}
1977
1978
1979#undef PyRun_String
1980PyAPI_FUNC(PyObject *)
1981PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
1982{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001983 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001984}
1985
1986#undef PyRun_SimpleString
1987PyAPI_FUNC(int)
1988PyRun_SimpleString(const char *s)
1989{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001990 return PyRun_SimpleStringFlags(s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001991}
1992
1993#undef Py_CompileString
1994PyAPI_FUNC(PyObject *)
1995Py_CompileString(const char *str, const char *p, int s)
1996{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00001997 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00001998}
1999
2000#undef PyRun_InteractiveOne
2001PyAPI_FUNC(int)
2002PyRun_InteractiveOne(FILE *f, const char *p)
2003{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002004 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002005}
2006
2007#undef PyRun_InteractiveLoop
2008PyAPI_FUNC(int)
2009PyRun_InteractiveLoop(FILE *f, const char *p)
2010{
Antoine Pitrouc7c96a92010-05-09 15:15:40 +00002011 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Heller1b046642006-04-18 18:51:06 +00002012}
2013
Anthony Baxterac6bd462006-04-13 02:06:09 +00002014#ifdef __cplusplus
2015}
2016#endif
2017