blob: 04dabc5c788e895cab60567fa512064f9ab5e4f9 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
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"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000021
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000025
Martin v. Löwis73d538b2003-03-05 15:13:47 +000026#ifdef HAVE_LANGINFO_H
27#include <locale.h>
28#include <langinfo.h>
29#endif
30
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000031#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000032#undef BYTE
33#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000034#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000035#endif
36
Neal Norwitz4281cef2006-03-04 19:58:13 +000037#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000038#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000039#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000040#define PRINT_TOTAL_REFS() fprintf(stderr, \
41 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
42 _Py_GetRefTotal())
43#endif
44
45#ifdef __cplusplus
46extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000047#endif
48
Martin v. Löwis790465f2008-04-05 20:41:37 +000049extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000050
Guido van Rossum82598051997-03-05 00:20:32 +000051extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000052
Guido van Rossumb73cc041993-11-01 16:28:59 +000053/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000054static void initmain(void);
55static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000056static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000057static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000058static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000059 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000060static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000061 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000062static void err_input(perrdetail *);
63static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000064static void call_py_exitfuncs(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000065static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000066extern void _PyUnicode_Init(void);
67extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000068extern int _PyLong_Init(void);
69extern void PyLong_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 */
Guido van Rossumd8faa362007-04-27 19:54:29 +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' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000081int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +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 */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000085int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000086int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000087
Christian Heimes33fe8092008-04-13 13:53:33 +000088/* PyModule_GetWarningsModule is no longer necessary as of 2.6
89since _warnings is builtin. This API should not be used. */
90PyObject *
91PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000092{
Christian Heimes33fe8092008-04-13 13:53:33 +000093 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000094}
Mark Hammonda43fd0c2003-02-19 00:33:33 +000095
Guido van Rossum25ce5661997-08-02 03:10:38 +000096static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000097
Thomas Wouters7e474022000-07-16 12:04:32 +000098/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000099
100int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000101Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000102{
103 return initialized;
104}
105
Guido van Rossum25ce5661997-08-02 03:10:38 +0000106/* Global initializations. Can be undone by Py_Finalize(). Don't
107 call this twice without an intervening Py_Finalize() call. When
108 initializations fail, a fatal error is issued and the function does
109 not return. On return, the first thread and interpreter state have
110 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000111
Guido van Rossum25ce5661997-08-02 03:10:38 +0000112 Locking: you must hold the interpreter lock while calling this.
113 (If the lock has not yet been initialized, that's equivalent to
114 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000117
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000118static int
119add_flag(int flag, const char *envs)
120{
121 int env = atoi(envs);
122 if (flag < env)
123 flag = env;
124 if (flag < 1)
125 flag = 1;
126 return flag;
127}
128
Christian Heimes5833a2f2008-10-30 21:40:04 +0000129#if defined(HAVE_LANGINFO_H) && defined(CODESET)
130static char*
131get_codeset(void)
132{
133 char* codeset;
134 PyObject *codec, *name;
135
136 codeset = nl_langinfo(CODESET);
137 if (!codeset || codeset[0] == '\0')
138 return NULL;
139
140 codec = _PyCodec_Lookup(codeset);
141 if (!codec)
142 goto error;
143
144 name = PyObject_GetAttrString(codec, "name");
145 Py_CLEAR(codec);
146 if (!name)
147 goto error;
148
149 codeset = strdup(_PyUnicode_AsString(name));
150 Py_DECREF(name);
151 return codeset;
152
153error:
154 Py_XDECREF(codec);
155 PyErr_Clear();
156 return NULL;
157}
158#endif
159
Guido van Rossuma027efa1997-05-05 20:56:21 +0000160void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000161Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000162{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000163 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000164 PyThreadState *tstate;
Guido van Rossum826d8972007-10-30 18:34:07 +0000165 PyObject *bimod, *sysmod, *pstderr;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000166 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000167#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000168 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000169#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000170 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000171
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000172 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000173 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000174 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000175
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000176#ifdef HAVE_SETLOCALE
177 /* Set up the LC_CTYPE locale, so we can obtain
178 the locale's charset without having to switch
179 locales. */
180 setlocale(LC_CTYPE, "");
181#endif
182
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000183 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000184 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000185 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000186 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000187 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000188 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Christian Heimes790c8232008-01-07 21:14:23 +0000189 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
190 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000191
Guido van Rossuma027efa1997-05-05 20:56:21 +0000192 interp = PyInterpreterState_New();
193 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000194 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000195
Guido van Rossuma027efa1997-05-05 20:56:21 +0000196 tstate = PyThreadState_New(interp);
197 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000198 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000199 (void) PyThreadState_Swap(tstate);
200
Guido van Rossum70d893a2001-08-16 08:21:42 +0000201 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000202
Neal Norwitzb2501f42002-12-31 03:42:13 +0000203 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000204 Py_FatalError("Py_Initialize: can't init frames");
205
Guido van Rossumddefaf32007-01-14 03:31:43 +0000206 if (!_PyLong_Init())
207 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000208
Christian Heimes9c4756e2008-05-26 13:22:05 +0000209 if (!PyByteArray_Init())
Neal Norwitz6968b052007-02-27 19:02:19 +0000210 Py_FatalError("Py_Initialize: can't init bytes");
211
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000212 _PyFloat_Init();
213
Guido van Rossum25ce5661997-08-02 03:10:38 +0000214 interp->modules = PyDict_New();
215 if (interp->modules == NULL)
216 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000217 interp->modules_reloading = PyDict_New();
218 if (interp->modules_reloading == NULL)
219 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000220
Guido van Rossumc94044c2000-03-10 23:03:54 +0000221 /* Init Unicode implementation; relies on the codec registry */
222 _PyUnicode_Init();
223
Barry Warsawf242aa02000-05-25 23:09:49 +0000224 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000225 if (bimod == NULL)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000226 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Martin v. Löwis1a214512008-06-11 05:26:20 +0000227 _PyImport_FixupExtension(bimod, "builtins", "builtins");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000228 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000229 if (interp->builtins == NULL)
230 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000231 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000232
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000233 /* initialize builtin exceptions */
234 _PyExc_Init();
235
Guido van Rossum25ce5661997-08-02 03:10:38 +0000236 sysmod = _PySys_Init();
237 if (sysmod == NULL)
238 Py_FatalError("Py_Initialize: can't initialize sys");
239 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000240 if (interp->sysdict == NULL)
241 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000242 Py_INCREF(interp->sysdict);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000243 _PyImport_FixupExtension(sysmod, "sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000244 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000245 PyDict_SetItemString(interp->sysdict, "modules",
246 interp->modules);
247
Guido van Rossum826d8972007-10-30 18:34:07 +0000248 /* Set up a preliminary stderr printer until we have enough
249 infrastructure for the io module in place. */
250 pstderr = PyFile_NewStdPrinter(fileno(stderr));
251 if (pstderr == NULL)
252 Py_FatalError("Py_Initialize: can't set preliminary stderr");
253 PySys_SetObject("stderr", pstderr);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000254 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000255
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000256 _PyImport_Init();
257
Just van Rossum52e14d62002-12-30 22:08:05 +0000258 _PyImportHooks_Init();
259
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000260 if (install_sigs)
261 initsigs(); /* Signal handling stuff, including initintr() */
Christian Heimes33fe8092008-04-13 13:53:33 +0000262
Georg Brandl86b2fb92008-07-16 03:43:04 +0000263 /* Initialize warnings. */
264 _PyWarnings_Init();
265 if (PySys_HasWarnOptions()) {
266 PyObject *warnings_module = PyImport_ImportModule("warnings");
267 if (!warnings_module)
268 PyErr_Clear();
269 Py_XDECREF(warnings_module);
270 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000271
272 initmain(); /* Module __main__ */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000273 if (initstdio() < 0)
274 Py_FatalError(
275 "Py_Initialize: can't initialize sys standard streams");
Benjamin Peterson791dc2f2008-09-05 23:27:15 +0000276 if (!Py_NoSiteFlag)
277 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000278
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000279 /* auto-thread-state API, if available */
280#ifdef WITH_THREAD
281 _PyGILState_Init(interp, tstate);
282#endif /* WITH_THREAD */
283
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000284#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000285 /* On Unix, set the file system encoding according to the
286 user's preference, if the CODESET names a well-known
287 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000288 initialized by other means. Also set the encoding of
289 stdin and stdout if these are terminals. */
290
Christian Heimes5833a2f2008-10-30 21:40:04 +0000291 codeset = get_codeset();
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000292 if (codeset) {
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000293 if (!Py_FileSystemDefaultEncoding)
294 Py_FileSystemDefaultEncoding = codeset;
295 else
296 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000297 }
298#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000299}
300
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000301void
302Py_Initialize(void)
303{
304 Py_InitializeEx(1);
305}
306
307
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000308#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000309extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000310#endif
311
Guido van Rossume8432ac2007-07-09 15:04:50 +0000312/* Flush stdout and stderr */
313
Neal Norwitz2bad9702007-08-27 06:19:22 +0000314static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000315flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000316{
317 PyObject *fout = PySys_GetObject("stdout");
318 PyObject *ferr = PySys_GetObject("stderr");
319 PyObject *tmp;
320
Christian Heimes2be03732007-11-15 02:26:46 +0000321 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000322 tmp = PyObject_CallMethod(fout, "flush", "");
323 if (tmp == NULL)
324 PyErr_Clear();
325 else
326 Py_DECREF(tmp);
327 }
328
Christian Heimes2be03732007-11-15 02:26:46 +0000329 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000330 tmp = PyObject_CallMethod(ferr, "flush", "");
331 if (tmp == NULL)
332 PyErr_Clear();
333 else
334 Py_DECREF(tmp);
335 }
336}
337
Guido van Rossum25ce5661997-08-02 03:10:38 +0000338/* Undo the effect of Py_Initialize().
339
340 Beware: if multiple interpreter and/or thread states exist, these
341 are not wiped out; only the current thread and interpreter state
342 are deleted. But since everything else is deleted, those other
343 interpreter and thread states should no longer be used.
344
345 (XXX We should do better, e.g. wipe out all interpreters and
346 threads.)
347
348 Locking: as above.
349
350*/
351
352void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000353Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000354{
355 PyInterpreterState *interp;
356 PyThreadState *tstate;
357
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000358 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000359 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000360
Tim Peters384fd102001-01-21 03:40:37 +0000361 /* The interpreter is still entirely intact at this point, and the
362 * exit funcs may be relying on that. In particular, if some thread
363 * or exit func is still waiting to do an import, the import machinery
364 * expects Py_IsInitialized() to return true. So don't say the
365 * interpreter is uninitialized until after the exit funcs have run.
366 * Note that Threading.py uses an exit func to do a join on all the
367 * threads created thru it, so this also protects pending imports in
368 * the threads created via Threading.
369 */
Collin Winter670e6922007-03-21 02:57:17 +0000370 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000371 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000372
Guido van Rossume8432ac2007-07-09 15:04:50 +0000373 /* Flush stdout+stderr */
374 flush_std_files();
375
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000376 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000377 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378 interp = tstate->interp;
379
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000380 /* Disable signal handling */
381 PyOS_FiniInterrupts();
382
Christian Heimes26855632008-01-27 23:50:43 +0000383 /* Clear type lookup cache */
384 PyType_ClearCache();
385
Guido van Rossume13ddc92003-04-17 17:29:22 +0000386 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000387 * before all modules are destroyed.
388 * XXX If a __del__ or weakref callback is triggered here, and tries to
389 * XXX import a module, bad things can happen, because Python no
390 * XXX longer believes it's initialized.
391 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
392 * XXX is easy to provoke that way. I've also seen, e.g.,
393 * XXX Exception exceptions.ImportError: 'No module named sha'
394 * XXX in <function callback at 0x008F5718> ignored
395 * XXX but I'm unclear on exactly how that one happens. In any case,
396 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000397 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000398 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000399#ifdef COUNT_ALLOCS
400 /* With COUNT_ALLOCS, it helps to run GC multiple times:
401 each collection might release some types from the type
402 list, so they become garbage. */
403 while (PyGC_Collect() > 0)
404 /* nothing */;
405#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000406
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000407 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000408 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000409
Guido van Rossume8432ac2007-07-09 15:04:50 +0000410 /* Flush stdout+stderr (again, in case more was printed) */
411 flush_std_files();
412
Guido van Rossume13ddc92003-04-17 17:29:22 +0000413 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000414 * new-style class definitions, for example.
415 * XXX This is disabled because it caused too many problems. If
416 * XXX a __del__ or weakref callback triggers here, Python code has
417 * XXX a hard time running, because even the sys module has been
418 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
419 * XXX One symptom is a sequence of information-free messages
420 * XXX coming from threads (if a __del__ or callback is invoked,
421 * XXX other threads can execute too, and any exception they encounter
422 * XXX triggers a comedy of errors as subsystem after subsystem
423 * XXX fails to find what it *expects* to find in sys to help report
424 * XXX the exception and consequent unexpected failures). I've also
425 * XXX seen segfaults then, after adding print statements to the
426 * XXX Python code getting called.
427 */
428#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000429 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000430#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000431
Guido van Rossum1707aad1997-12-08 23:43:45 +0000432 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
433 _PyImport_Fini();
434
435 /* Debugging stuff */
436#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000437 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000438#endif
439
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000440 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000441
Tim Peters9cf25ce2003-04-17 15:21:01 +0000442#ifdef Py_TRACE_REFS
443 /* Display all objects still alive -- this can invoke arbitrary
444 * __repr__ overrides, so requires a mostly-intact interpreter.
445 * Alas, a lot of stuff may still be alive now that will be cleaned
446 * up later.
447 */
Tim Peters269b2a62003-04-17 19:52:29 +0000448 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000449 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000450#endif /* Py_TRACE_REFS */
451
Guido van Rossumd922fa42003-04-15 14:10:09 +0000452 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000453 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000454
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000455 /* Now we decref the exception classes. After this point nothing
456 can raise an exception. That's okay, because each Fini() method
457 below has been checked to make sure no exceptions are ever
458 raised.
459 */
460
461 _PyExc_Fini();
462
Christian Heimes7d2ff882007-11-30 14:35:04 +0000463 /* Cleanup auto-thread-state */
464#ifdef WITH_THREAD
465 _PyGILState_Fini();
466#endif /* WITH_THREAD */
467
Guido van Rossumd922fa42003-04-15 14:10:09 +0000468 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000469 PyThreadState_Swap(NULL);
470 PyInterpreterState_Delete(interp);
471
Guido van Rossumd922fa42003-04-15 14:10:09 +0000472 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000473 PyMethod_Fini();
474 PyFrame_Fini();
475 PyCFunction_Fini();
476 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000477 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000478 PySet_Fini();
Christian Heimes72b710a2008-05-26 13:28:38 +0000479 PyBytes_Fini();
Christian Heimes9c4756e2008-05-26 13:22:05 +0000480 PyByteArray_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000481 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000482 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000483 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000484
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000485 /* Cleanup Unicode implementation */
486 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000487
Christian Heimesc8967002007-11-30 10:18:26 +0000488 /* reset file system default encoding */
489 if (!Py_HasFileSystemDefaultEncoding) {
490 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000491 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000492 }
493
Guido van Rossumcc283f51997-08-05 02:22:03 +0000494 /* XXX Still allocated:
495 - various static ad-hoc pointers to interned strings
496 - int and float free list blocks
497 - whatever various modules and libraries allocate
498 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000499
500 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000501
Tim Peters269b2a62003-04-17 19:52:29 +0000502#ifdef Py_TRACE_REFS
503 /* Display addresses (& refcnts) of all objects still alive.
504 * An address can be used to find the repr of the object, printed
505 * above by _Py_PrintReferences.
506 */
507 if (Py_GETENV("PYTHONDUMPREFS"))
508 _Py_PrintReferenceAddresses(stderr);
509#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000510#ifdef PYMALLOC_DEBUG
511 if (Py_GETENV("PYTHONMALLOCSTATS"))
512 _PyObject_DebugMallocStats();
513#endif
514
Guido van Rossumcc283f51997-08-05 02:22:03 +0000515 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000516}
517
518/* Create and initialize a new interpreter and thread, and return the
519 new thread. This requires that Py_Initialize() has been called
520 first.
521
522 Unsuccessful initialization yields a NULL pointer. Note that *no*
523 exception information is available even in this case -- the
524 exception information is held in the thread, and there is no
525 thread.
526
527 Locking: as above.
528
529*/
530
531PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000532Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000533{
534 PyInterpreterState *interp;
535 PyThreadState *tstate, *save_tstate;
536 PyObject *bimod, *sysmod;
537
538 if (!initialized)
539 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
540
541 interp = PyInterpreterState_New();
542 if (interp == NULL)
543 return NULL;
544
545 tstate = PyThreadState_New(interp);
546 if (tstate == NULL) {
547 PyInterpreterState_Delete(interp);
548 return NULL;
549 }
550
551 save_tstate = PyThreadState_Swap(tstate);
552
553 /* XXX The following is lax in error checking */
554
555 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000556 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000557
Georg Brandl1a3284e2007-12-02 09:40:06 +0000558 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000560 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000561 if (interp->builtins == NULL)
562 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000563 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000565
566 /* initialize builtin exceptions */
567 _PyExc_Init();
568
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569 sysmod = _PyImport_FindExtension("sys", "sys");
570 if (bimod != NULL && sysmod != NULL) {
Christian Heimes6a27efa2008-10-30 21:48:26 +0000571 PyObject *pstderr;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000573 if (interp->sysdict == NULL)
574 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575 Py_INCREF(interp->sysdict);
576 PySys_SetPath(Py_GetPath());
577 PyDict_SetItemString(interp->sysdict, "modules",
578 interp->modules);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000579 /* Set up a preliminary stderr printer until we have enough
580 infrastructure for the io module in place. */
581 pstderr = PyFile_NewStdPrinter(fileno(stderr));
582 if (pstderr == NULL)
583 Py_FatalError("Py_Initialize: can't set preliminary stderr");
584 PySys_SetObject("stderr", pstderr);
585 PySys_SetObject("__stderr__", pstderr);
586
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000587 _PyImportHooks_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000588 if (initstdio() < 0)
589 Py_FatalError(
590 "Py_Initialize: can't initialize sys standard streams");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000592 if (!Py_NoSiteFlag)
593 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594 }
595
596 if (!PyErr_Occurred())
597 return tstate;
598
Thomas Wouters89f507f2006-12-13 04:49:30 +0000599handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000600 /* Oops, it didn't work. Undo it all. */
601
602 PyErr_Print();
603 PyThreadState_Clear(tstate);
604 PyThreadState_Swap(save_tstate);
605 PyThreadState_Delete(tstate);
606 PyInterpreterState_Delete(interp);
607
608 return NULL;
609}
610
611/* Delete an interpreter and its last thread. This requires that the
612 given thread state is current, that the thread has no remaining
613 frames, and that it is its interpreter's only remaining thread.
614 It is a fatal error to violate these constraints.
615
616 (Py_Finalize() doesn't have these constraints -- it zaps
617 everything, regardless.)
618
619 Locking: as above.
620
621*/
622
623void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000624Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000625{
626 PyInterpreterState *interp = tstate->interp;
627
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000628 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629 Py_FatalError("Py_EndInterpreter: thread is not current");
630 if (tstate->frame != NULL)
631 Py_FatalError("Py_EndInterpreter: thread still has a frame");
632 if (tstate != interp->tstate_head || tstate->next != NULL)
633 Py_FatalError("Py_EndInterpreter: not the last thread");
634
635 PyImport_Cleanup();
636 PyInterpreterState_Clear(interp);
637 PyThreadState_Swap(NULL);
638 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000639}
640
Martin v. Löwis790465f2008-04-05 20:41:37 +0000641static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000642
643void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000644Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000645{
646 if (pn && *pn)
647 progname = pn;
648}
649
Martin v. Löwis790465f2008-04-05 20:41:37 +0000650wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000651Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000652{
653 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000654}
655
Martin v. Löwis790465f2008-04-05 20:41:37 +0000656static wchar_t *default_home = NULL;
657static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000658
659void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000660Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000661{
662 default_home = home;
663}
664
Martin v. Löwis790465f2008-04-05 20:41:37 +0000665wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000666Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000667{
Martin v. Löwis790465f2008-04-05 20:41:37 +0000668 wchar_t *home = default_home;
669 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
670 char* chome = Py_GETENV("PYTHONHOME");
671 if (chome) {
672 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
673 if (r != (size_t)-1 && r <= PATH_MAX)
674 home = env_home;
675 }
676
677 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000678 return home;
679}
680
Guido van Rossum6135a871995-01-09 17:53:26 +0000681/* Create __main__ module */
682
683static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000684initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000685{
Guido van Rossum82598051997-03-05 00:20:32 +0000686 PyObject *m, *d;
687 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000688 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000689 Py_FatalError("can't create __main__ module");
690 d = PyModule_GetDict(m);
691 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000692 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000693 if (bimod == NULL ||
694 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000695 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000696 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000697 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000698}
699
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000700/* Import the site module (not into __main__ though) */
701
702static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000703initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000704{
705 PyObject *m, *f;
706 m = PyImport_ImportModule("site");
707 if (m == NULL) {
708 f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +0000709 if (f == NULL || f == Py_None)
710 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000711 if (Py_VerboseFlag) {
712 PyFile_WriteString(
713 "'import site' failed; traceback:\n", f);
714 PyErr_Print();
715 }
716 else {
717 PyFile_WriteString(
718 "'import site' failed; use -v for traceback\n", f);
719 PyErr_Clear();
720 }
721 }
722 else {
723 Py_DECREF(m);
724 }
725}
726
Georg Brandl1a3284e2007-12-02 09:40:06 +0000727/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000728static int
729initstdio(void)
730{
731 PyObject *iomod = NULL, *wrapper;
732 PyObject *bimod = NULL;
733 PyObject *m;
734 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000735 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000736 PyObject * encoding_attr;
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +0000737 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000738
739 /* Hack to avoid a nasty recursion issue when Python is invoked
740 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
741 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
742 goto error;
743 }
744 Py_DECREF(m);
745
746 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
747 goto error;
748 }
749 Py_DECREF(m);
750
Georg Brandl1a3284e2007-12-02 09:40:06 +0000751 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000752 goto error;
753 }
754
755 if (!(iomod = PyImport_ImportModule("io"))) {
756 goto error;
757 }
758 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
759 goto error;
760 }
761
Georg Brandl1a3284e2007-12-02 09:40:06 +0000762 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000763 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
764 goto error;
765 }
766
Martin v. Löwis0f599892008-06-02 11:13:03 +0000767 encoding = Py_GETENV("PYTHONIOENCODING");
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000768 errors = NULL;
Martin v. Löwis0f599892008-06-02 11:13:03 +0000769 if (encoding) {
770 encoding = strdup(encoding);
771 errors = strchr(encoding, ':');
772 if (errors) {
773 *errors = '\0';
774 errors++;
775 }
776 }
777
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000778 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000779 fd = fileno(stdin);
780 /* Under some conditions stdin, stdout and stderr may not be connected
781 * and fileno() may point to an invalid file descriptor. For example
782 * GUI apps don't have valid standard streams by default.
783 */
784 if (fd < 0) {
785#ifdef MS_WINDOWS
786 std = Py_None;
787 Py_INCREF(std);
788#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000789 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000790#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000791 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000792 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000793 if (!(std = PyFile_FromFd(fd, "<stdin>", "r", -1, encoding,
794 errors, "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000795 goto error;
796 }
797 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000798 PySys_SetObject("__stdin__", std);
799 PySys_SetObject("stdin", std);
800 Py_DECREF(std);
801
802 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000803 fd = fileno(stdout);
804 if (fd < 0) {
805#ifdef MS_WINDOWS
806 std = Py_None;
807 Py_INCREF(std);
808#else
809 goto error;
810#endif
811 }
812 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000813 if (!(std = PyFile_FromFd(fd, "<stdout>", "w", -1, encoding,
814 errors, "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000815 goto error;
816 }
817 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000818 PySys_SetObject("__stdout__", std);
819 PySys_SetObject("stdout", std);
820 Py_DECREF(std);
821
Guido van Rossum98297ee2007-11-06 21:34:58 +0000822#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000823 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000824 fd = fileno(stderr);
825 if (fd < 0) {
826#ifdef MS_WINDOWS
827 std = Py_None;
828 Py_INCREF(std);
829#else
830 goto error;
831#endif
832 }
833 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000834 if (!(std = PyFile_FromFd(fd, "<stderr>", "w", -1, encoding,
Georg Brandl559e5d72008-06-11 18:37:52 +0000835 "backslashreplace", "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000836 goto error;
837 }
838 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000839
840 /* Same as hack above, pre-import stderr's codec to avoid recursion
841 when import.c tries to write to stderr in verbose mode. */
842 encoding_attr = PyObject_GetAttrString(std, "encoding");
843 if (encoding_attr != NULL) {
844 const char * encoding;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000845 encoding = _PyUnicode_AsString(encoding_attr);
Trent Nelson39e307e2008-03-19 06:45:48 +0000846 if (encoding != NULL) {
847 _PyCodec_Lookup(encoding);
848 }
849 }
850 PyErr_Clear(); /* Not a fatal error if codec isn't available */
851
Christian Heimesdb233082007-11-13 02:34:21 +0000852 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000853 PySys_SetObject("stderr", std);
854 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000855#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000856
Christian Heimes58cb1b82007-11-13 02:19:40 +0000857 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000858 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000859 status = -1;
860 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000861
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000862 if (encoding)
863 free(encoding);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000864 Py_XDECREF(bimod);
865 Py_XDECREF(iomod);
866 return status;
867}
868
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000869/* Parse input from a file and execute it */
870
871int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000872PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000873 PyCompilerFlags *flags)
874{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000875 if (filename == NULL)
876 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000877 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000878 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000879 if (closeit)
880 fclose(fp);
881 return err;
882 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000883 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000884 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000885}
886
887int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000888PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000889{
Guido van Rossum82598051997-03-05 00:20:32 +0000890 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000891 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000892 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000893
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000894 if (flags == NULL) {
895 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000896 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000897 }
Guido van Rossum82598051997-03-05 00:20:32 +0000898 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000899 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000900 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000901 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000902 }
Guido van Rossum82598051997-03-05 00:20:32 +0000903 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000904 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000905 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000906 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000907 }
908 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000909 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000910 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000911 if (ret == E_EOF)
912 return 0;
913 /*
914 if (ret == E_NOMEM)
915 return -1;
916 */
917 }
918}
919
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000920/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000921#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000922 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Guido van Rossum45aecf42006-03-15 04:58:47 +0000923 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000924
Thomas Wouters89f507f2006-12-13 04:49:30 +0000925#if 0
926/* Keep an example of flags with future keyword support. */
927#define PARSER_FLAGS(flags) \
928 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
929 PyPARSE_DONT_IMPLY_DEDENT : 0) \
930 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
931 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
932#endif
933
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000934int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000935PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000936{
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000937 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +0000939 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000940 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000941 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000942
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000943 if (fp == stdin) {
944 /* Fetch encoding from sys.stdin */
945 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +0000946 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000947 return -1;
948 oenc = PyObject_GetAttrString(v, "encoding");
949 if (!oenc)
950 return -1;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000951 enc = _PyUnicode_AsString(oenc);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000952 }
Guido van Rossum82598051997-03-05 00:20:32 +0000953 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000954 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000955 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000956 if (v == NULL)
957 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000958 else if (PyUnicode_Check(v))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000959 ps1 = _PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000960 }
Guido van Rossum82598051997-03-05 00:20:32 +0000961 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000962 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000963 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000964 if (w == NULL)
965 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000966 else if (PyUnicode_Check(w))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000967 ps2 = _PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000968 }
Neal Norwitz9589ee22006-03-04 19:01:22 +0000969 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000970 if (arena == NULL) {
971 Py_XDECREF(v);
972 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000973 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000974 return -1;
975 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000976 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000977 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000978 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +0000979 Py_XDECREF(v);
980 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000981 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000982 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000983 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000984 if (errcode == E_EOF) {
985 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000986 return E_EOF;
987 }
Guido van Rossum82598051997-03-05 00:20:32 +0000988 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000989 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000990 }
Guido van Rossum82598051997-03-05 00:20:32 +0000991 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000992 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000993 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000994 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000995 }
Guido van Rossum82598051997-03-05 00:20:32 +0000996 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000997 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +0000998 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +0000999 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001000 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001001 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001002 return -1;
1003 }
Guido van Rossum82598051997-03-05 00:20:32 +00001004 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001005 return 0;
1006}
1007
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001008/* Check whether a file maybe a pyc file: Look at the extension,
1009 the file type, and, if we may close it, at the first few bytes. */
1010
1011static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001012maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001013{
1014 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1015 return 1;
1016
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001017 /* Only look into the file if we are allowed to close it, since
1018 it then should also be seekable. */
1019 if (closeit) {
1020 /* Read only two bytes of the magic. If the file was opened in
1021 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1022 be read as they are on disk. */
1023 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1024 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001025 /* Mess: In case of -x, the stream is NOT at its start now,
1026 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001027 which makes the current stream position formally undefined,
1028 and a x-platform nightmare.
1029 Unfortunately, we have no direct way to know whether -x
1030 was specified. So we use a terrible hack: if the current
1031 stream position is not 0, we assume -x was specified, and
1032 give up. Bug 132850 on SourceForge spells out the
1033 hopelessness of trying anything else (fseek and ftell
1034 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001035 */
Tim Peters3e876562001-02-11 04:35:39 +00001036 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001037 if (ftell(fp) == 0) {
1038 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001039 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001040 ispyc = 1;
1041 rewind(fp);
1042 }
Tim Peters3e876562001-02-11 04:35:39 +00001043 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001044 }
1045 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001046}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001047
Guido van Rossum0df002c2000-08-27 19:21:52 +00001048int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001049PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001050 PyCompilerFlags *flags)
1051{
Guido van Rossum82598051997-03-05 00:20:32 +00001052 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001053 const char *ext;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001054 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001055
Guido van Rossum82598051997-03-05 00:20:32 +00001056 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001057 if (m == NULL)
1058 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001059 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001060 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001061 PyObject *f;
1062 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001063 if (f == NULL)
1064 return -1;
1065 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1066 Py_DECREF(f);
1067 return -1;
1068 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001069 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001070 Py_DECREF(f);
1071 }
Guido van Rossumfdef2711994-09-14 13:31:04 +00001072 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001073 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001074 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001075 if (closeit)
1076 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001077 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001078 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001079 ret = -1;
1080 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001081 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001082 /* Turn on optimization if a .pyo file is given */
1083 if (strcmp(ext, ".pyo") == 0)
1084 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001085 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001086 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001087 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001088 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001089 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001090 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001091 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001092 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001093 ret = -1;
1094 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001095 }
Guido van Rossum82598051997-03-05 00:20:32 +00001096 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001097 ret = 0;
1098 done:
1099 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1100 PyErr_Clear();
1101 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001102}
1103
1104int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001105PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001106{
Guido van Rossum82598051997-03-05 00:20:32 +00001107 PyObject *m, *d, *v;
1108 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001109 if (m == NULL)
1110 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001111 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001112 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001113 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001114 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001115 return -1;
1116 }
Guido van Rossum82598051997-03-05 00:20:32 +00001117 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001118 return 0;
1119}
1120
Barry Warsaw035574d1997-08-29 22:07:17 +00001121static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001122parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1123 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001124{
1125 long hold;
1126 PyObject *v;
1127
1128 /* old style errors */
1129 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001130 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001131 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001132
1133 /* new style errors. `err' is an instance */
1134
1135 if (! (v = PyObject_GetAttrString(err, "msg")))
1136 goto finally;
1137 *message = v;
1138
1139 if (!(v = PyObject_GetAttrString(err, "filename")))
1140 goto finally;
1141 if (v == Py_None)
1142 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001143 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001144 goto finally;
1145
1146 Py_DECREF(v);
1147 if (!(v = PyObject_GetAttrString(err, "lineno")))
1148 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001149 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001150 Py_DECREF(v);
1151 v = NULL;
1152 if (hold < 0 && PyErr_Occurred())
1153 goto finally;
1154 *lineno = (int)hold;
1155
1156 if (!(v = PyObject_GetAttrString(err, "offset")))
1157 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001158 if (v == Py_None) {
1159 *offset = -1;
1160 Py_DECREF(v);
1161 v = NULL;
1162 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001163 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001164 Py_DECREF(v);
1165 v = NULL;
1166 if (hold < 0 && PyErr_Occurred())
1167 goto finally;
1168 *offset = (int)hold;
1169 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001170
1171 if (!(v = PyObject_GetAttrString(err, "text")))
1172 goto finally;
1173 if (v == Py_None)
1174 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001175 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001176 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001177 goto finally;
1178 Py_DECREF(v);
1179 return 1;
1180
1181finally:
1182 Py_XDECREF(v);
1183 return 0;
1184}
1185
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001186void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001187PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001188{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001189 PyErr_PrintEx(1);
1190}
1191
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001192static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001193print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001194{
1195 char *nl;
1196 if (offset >= 0) {
1197 if (offset > 0 && offset == (int)strlen(text))
1198 offset--;
1199 for (;;) {
1200 nl = strchr(text, '\n');
1201 if (nl == NULL || nl-text >= offset)
1202 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001203 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001204 text = nl+1;
1205 }
1206 while (*text == ' ' || *text == '\t') {
1207 text++;
1208 offset--;
1209 }
1210 }
1211 PyFile_WriteString(" ", f);
1212 PyFile_WriteString(text, f);
1213 if (*text == '\0' || text[strlen(text)-1] != '\n')
1214 PyFile_WriteString("\n", f);
1215 if (offset == -1)
1216 return;
1217 PyFile_WriteString(" ", f);
1218 offset--;
1219 while (offset > 0) {
1220 PyFile_WriteString(" ", f);
1221 offset--;
1222 }
1223 PyFile_WriteString("^\n", f);
1224}
1225
Guido van Rossum66e8e862001-03-23 17:54:43 +00001226static void
1227handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001228{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001229 PyObject *exception, *value, *tb;
1230 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001231
Guido van Rossumd8faa362007-04-27 19:54:29 +00001232 if (Py_InspectFlag)
1233 /* Don't exit if -i flag was given. This flag is set to 0
1234 * when entering interactive mode for inspecting. */
1235 return;
1236
Guido van Rossum66e8e862001-03-23 17:54:43 +00001237 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001238 fflush(stdout);
1239 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001240 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001241 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001242 /* The error code should be in the `code' attribute. */
1243 PyObject *code = PyObject_GetAttrString(value, "code");
1244 if (code) {
1245 Py_DECREF(value);
1246 value = code;
1247 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001248 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001249 }
1250 /* If we failed to dig out the 'code' attribute,
1251 just let the else clause below print the error. */
1252 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001253 if (PyLong_Check(value))
1254 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001255 else {
1256 PyObject_Print(value, stderr, Py_PRINT_RAW);
1257 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001258 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001259 }
Tim Peterscf615b52003-04-19 18:47:02 +00001260 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001261 /* Restore and clear the exception info, in order to properly decref
1262 * the exception, value, and traceback. If we just exit instead,
1263 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1264 * some finalizers from running.
1265 */
Tim Peterscf615b52003-04-19 18:47:02 +00001266 PyErr_Restore(exception, value, tb);
1267 PyErr_Clear();
1268 Py_Exit(exitcode);
1269 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001270}
1271
1272void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001273PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001274{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001275 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001276
1277 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1278 handle_system_exit();
1279 }
Guido van Rossum82598051997-03-05 00:20:32 +00001280 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001281 if (exception == NULL)
1282 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001283 PyErr_NormalizeException(&exception, &v, &tb);
Antoine Pitroue2dffc02008-08-26 22:02:58 +00001284 if (tb == NULL) {
1285 tb = Py_None;
1286 Py_INCREF(tb);
1287 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001288 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001289 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001290 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001291 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001292 if (set_sys_last_vars) {
1293 PySys_SetObject("last_type", exception);
1294 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001295 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001296 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001297 hook = PySys_GetObject("excepthook");
1298 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001299 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001300 PyObject *result = PyEval_CallObject(hook, args);
1301 if (result == NULL) {
1302 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001303 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1304 handle_system_exit();
1305 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001306 PyErr_Fetch(&exception2, &v2, &tb2);
1307 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001308 /* It should not be possible for exception2 or v2
1309 to be NULL. However PyErr_Display() can't
1310 tolerate NULLs, so just be safe. */
1311 if (exception2 == NULL) {
1312 exception2 = Py_None;
1313 Py_INCREF(exception2);
1314 }
1315 if (v2 == NULL) {
1316 v2 = Py_None;
1317 Py_INCREF(v2);
1318 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001319 fflush(stdout);
1320 PySys_WriteStderr("Error in sys.excepthook:\n");
1321 PyErr_Display(exception2, v2, tb2);
1322 PySys_WriteStderr("\nOriginal exception was:\n");
1323 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001324 Py_DECREF(exception2);
1325 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001326 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001327 }
1328 Py_XDECREF(result);
1329 Py_XDECREF(args);
1330 } else {
1331 PySys_WriteStderr("sys.excepthook is missing\n");
1332 PyErr_Display(exception, v, tb);
1333 }
1334 Py_XDECREF(exception);
1335 Py_XDECREF(v);
1336 Py_XDECREF(tb);
1337}
1338
Benjamin Petersone6528212008-07-15 15:32:09 +00001339static void
1340print_exception(PyObject *f, PyObject *value)
1341{
1342 int err = 0;
1343 PyObject *type, *tb;
1344
Benjamin Peterson26582602008-08-23 20:08:07 +00001345 if (!PyExceptionInstance_Check(value)) {
1346 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1347 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1348 PyFile_WriteString(" found\n", f);
1349 return;
1350 }
1351
Benjamin Petersone6528212008-07-15 15:32:09 +00001352 Py_INCREF(value);
1353 fflush(stdout);
1354 type = (PyObject *) Py_TYPE(value);
1355 tb = PyException_GetTraceback(value);
1356 if (tb && tb != Py_None)
1357 err = PyTraceBack_Print(tb, f);
1358 if (err == 0 &&
1359 PyObject_HasAttrString(value, "print_file_and_line"))
1360 {
1361 PyObject *message;
1362 const char *filename, *text;
1363 int lineno, offset;
1364 if (!parse_syntax_error(value, &message, &filename,
1365 &lineno, &offset, &text))
1366 PyErr_Clear();
1367 else {
1368 char buf[10];
1369 PyFile_WriteString(" File \"", f);
1370 if (filename == NULL)
1371 PyFile_WriteString("<string>", f);
1372 else
1373 PyFile_WriteString(filename, f);
1374 PyFile_WriteString("\", line ", f);
1375 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1376 PyFile_WriteString(buf, f);
1377 PyFile_WriteString("\n", f);
1378 if (text != NULL)
1379 print_error_text(f, offset, text);
1380 Py_DECREF(value);
1381 value = message;
1382 /* Can't be bothered to check all those
1383 PyFile_WriteString() calls */
1384 if (PyErr_Occurred())
1385 err = -1;
1386 }
1387 }
1388 if (err) {
1389 /* Don't do anything else */
1390 }
1391 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001392 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001393 char* className;
1394 assert(PyExceptionClass_Check(type));
1395 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001396 if (className != NULL) {
1397 char *dot = strrchr(className, '.');
1398 if (dot != NULL)
1399 className = dot+1;
1400 }
1401
1402 moduleName = PyObject_GetAttrString(type, "__module__");
1403 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1404 {
1405 Py_DECREF(moduleName);
1406 err = PyFile_WriteString("<unknown>", f);
1407 }
1408 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001409 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001410 if (modstr && strcmp(modstr, "builtins"))
1411 {
1412 err = PyFile_WriteString(modstr, f);
1413 err += PyFile_WriteString(".", f);
1414 }
1415 Py_DECREF(moduleName);
1416 }
1417 if (err == 0) {
1418 if (className == NULL)
1419 err = PyFile_WriteString("<unknown>", f);
1420 else
1421 err = PyFile_WriteString(className, f);
1422 }
1423 }
1424 if (err == 0 && (value != Py_None)) {
1425 PyObject *s = PyObject_Str(value);
1426 /* only print colon if the str() of the
1427 object is not the empty string
1428 */
1429 if (s == NULL)
1430 err = -1;
1431 else if (!PyUnicode_Check(s) ||
1432 PyUnicode_GetSize(s) != 0)
1433 err = PyFile_WriteString(": ", f);
1434 if (err == 0)
1435 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1436 Py_XDECREF(s);
1437 }
1438 /* try to write a newline in any case */
1439 err += PyFile_WriteString("\n", f);
1440 Py_XDECREF(tb);
1441 Py_DECREF(value);
1442 /* If an error happened here, don't show it.
1443 XXX This is wrong, but too many callers rely on this behavior. */
1444 if (err != 0)
1445 PyErr_Clear();
1446}
1447
1448static const char *cause_message =
1449 "\nThe above exception was the direct cause "
1450 "of the following exception:\n\n";
1451
1452static const char *context_message =
1453 "\nDuring handling of the above exception, "
1454 "another exception occurred:\n\n";
1455
1456static void
1457print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1458{
1459 int err = 0, res;
1460 PyObject *cause, *context;
1461
1462 if (seen != NULL) {
1463 /* Exception chaining */
1464 if (PySet_Add(seen, value) == -1)
1465 PyErr_Clear();
1466 else if (PyExceptionInstance_Check(value)) {
1467 cause = PyException_GetCause(value);
1468 context = PyException_GetContext(value);
1469 if (cause) {
1470 res = PySet_Contains(seen, cause);
1471 if (res == -1)
1472 PyErr_Clear();
1473 if (res == 0) {
1474 print_exception_recursive(
1475 f, cause, seen);
1476 err |= PyFile_WriteString(
1477 cause_message, f);
1478 }
1479 }
1480 if (context) {
1481 res = PySet_Contains(seen, context);
1482 if (res == -1)
1483 PyErr_Clear();
1484 if (res == 0) {
1485 print_exception_recursive(
1486 f, context, seen);
1487 err |= PyFile_WriteString(
1488 context_message, f);
1489 }
1490 }
1491 Py_XDECREF(context);
1492 Py_XDECREF(cause);
1493 }
1494 }
1495 print_exception(f, value);
1496 if (err != 0)
1497 PyErr_Clear();
1498}
1499
Thomas Wouters477c8d52006-05-27 19:21:47 +00001500void
1501PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001502{
Benjamin Petersone6528212008-07-15 15:32:09 +00001503 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001504 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001505 if (f == Py_None) {
1506 /* pass */
1507 }
1508 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001509 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001510 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001511 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001512 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001513 /* We choose to ignore seen being possibly NULL, and report
1514 at least the main exception (it could be a MemoryError).
1515 */
1516 seen = PySet_New(NULL);
1517 if (seen == NULL)
1518 PyErr_Clear();
1519 print_exception_recursive(f, value, seen);
1520 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001521 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001522}
1523
Guido van Rossum82598051997-03-05 00:20:32 +00001524PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001525PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001526 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001527{
Neal Norwitze92fba02006-03-04 18:52:26 +00001528 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001529 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001530 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001531 if (arena == NULL)
1532 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001533
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001534 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001535 if (mod != NULL)
1536 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001537 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001538 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001539}
1540
1541PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001542PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001543 PyObject *locals, int closeit, PyCompilerFlags *flags)
1544{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001545 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001546 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001547 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001548 if (arena == NULL)
1549 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001550
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001551 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001552 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001553 if (closeit)
1554 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001555 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001556 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001557 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001558 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001559 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001560 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001562}
1563
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001564static void
1565flush_io(void)
1566{
1567 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001568 PyObject *type, *value, *traceback;
1569
1570 /* Save the current exception */
1571 PyErr_Fetch(&type, &value, &traceback);
1572
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001573 f = PySys_GetObject("stderr");
1574 if (f != NULL) {
1575 r = PyObject_CallMethod(f, "flush", "");
1576 if (r)
1577 Py_DECREF(r);
1578 else
1579 PyErr_Clear();
1580 }
1581 f = PySys_GetObject("stdout");
1582 if (f != NULL) {
1583 r = PyObject_CallMethod(f, "flush", "");
1584 if (r)
1585 Py_DECREF(r);
1586 else
1587 PyErr_Clear();
1588 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001589
1590 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001591}
1592
Guido van Rossum82598051997-03-05 00:20:32 +00001593static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001594run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001595 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001596{
Guido van Rossum82598051997-03-05 00:20:32 +00001597 PyCodeObject *co;
1598 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001599 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001600 if (co == NULL)
1601 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001602 v = PyEval_EvalCode(co, globals, locals);
1603 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001604 return v;
1605}
1606
Guido van Rossum82598051997-03-05 00:20:32 +00001607static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001608run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001609 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001610{
Guido van Rossum82598051997-03-05 00:20:32 +00001611 PyCodeObject *co;
1612 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001613 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001614 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001615
Guido van Rossum82598051997-03-05 00:20:32 +00001616 magic = PyMarshal_ReadLongFromFile(fp);
1617 if (magic != PyImport_GetMagicNumber()) {
1618 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001619 "Bad magic number in .pyc file");
1620 return NULL;
1621 }
Guido van Rossum82598051997-03-05 00:20:32 +00001622 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001623 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001624 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001625 if (v == NULL || !PyCode_Check(v)) {
1626 Py_XDECREF(v);
1627 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001628 "Bad code object in .pyc file");
1629 return NULL;
1630 }
Guido van Rossum82598051997-03-05 00:20:32 +00001631 co = (PyCodeObject *)v;
1632 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001633 if (v && flags)
1634 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001635 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001636 return v;
1637}
1638
Guido van Rossum82598051997-03-05 00:20:32 +00001639PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001640Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001641 PyCompilerFlags *flags)
1642{
Guido van Rossum82598051997-03-05 00:20:32 +00001643 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001644 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001645 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001646 if (arena == NULL)
1647 return NULL;
1648
1649 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001650 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001651 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001652 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001653 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001654 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001655 PyObject *result = PyAST_mod2obj(mod);
1656 PyArena_Free(arena);
1657 return result;
1658 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001659 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001660 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001661 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001662}
1663
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001664struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001665Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001666{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001667 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001668 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001669 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001670 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001671 if (arena == NULL)
1672 return NULL;
1673
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001674 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001675 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001676 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001677 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001678 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001679 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001680 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001681 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001682 return st;
1683}
1684
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001685/* Preferred access to parser is through AST. */
1686mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001687PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001688 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001689{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001690 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001691 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001693 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001694
1695 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001696 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001697 &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001698 if (flags == NULL) {
1699 localflags.cf_flags = 0;
1700 flags = &localflags;
1701 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001702 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001703 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001704 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001705 PyNode_Free(n);
1706 return mod;
1707 }
1708 else {
1709 err_input(&err);
1710 return NULL;
1711 }
1712}
1713
1714mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001715PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1716 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001717 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001718 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001719{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001720 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001721 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001722 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001723 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001724
Christian Heimes4d6ec852008-03-26 22:34:47 +00001725 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001726 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001727 start, ps1, ps2, &err, &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001728 if (flags == NULL) {
1729 localflags.cf_flags = 0;
1730 flags = &localflags;
1731 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001732 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001733 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001734 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001735 PyNode_Free(n);
1736 return mod;
1737 }
1738 else {
1739 err_input(&err);
1740 if (errcode)
1741 *errcode = err.error;
1742 return NULL;
1743 }
1744}
1745
Guido van Rossuma110aa61994-08-29 12:50:44 +00001746/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001747
Guido van Rossuma110aa61994-08-29 12:50:44 +00001748node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001749PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001750{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001751 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001752 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1753 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001754 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001755 if (n == NULL)
1756 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001757
Guido van Rossuma110aa61994-08-29 12:50:44 +00001758 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001759}
1760
Guido van Rossuma110aa61994-08-29 12:50:44 +00001761/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001762
Guido van Rossuma110aa61994-08-29 12:50:44 +00001763node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001764PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001765{
Tim Petersfe2127d2001-07-16 05:37:24 +00001766 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001767 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1768 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001769 if (n == NULL)
1770 err_input(&err);
1771 return n;
1772}
1773
1774node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001775PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001776 int start, int flags)
1777{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001778 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001779 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1780 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001781 if (n == NULL)
1782 err_input(&err);
1783 return n;
1784}
1785
1786node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001787PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001788{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001789 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001790}
1791
Guido van Rossum66ebd912003-04-17 16:02:26 +00001792/* May want to move a more generalized form of this to parsetok.c or
1793 even parser modules. */
1794
1795void
1796PyParser_SetError(perrdetail *err)
1797{
1798 err_input(err);
1799}
1800
Guido van Rossuma110aa61994-08-29 12:50:44 +00001801/* Set the error appropriate to the given input error code (see errcode.h) */
1802
1803static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001804err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001805{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001806 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001807 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001808 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001809 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001810 switch (err->error) {
1811 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001812 errtype = PyExc_IndentationError;
1813 if (err->expected == INDENT)
1814 msg = "expected an indented block";
1815 else if (err->token == INDENT)
1816 msg = "unexpected indent";
1817 else if (err->token == DEDENT)
1818 msg = "unexpected unindent";
1819 else {
1820 errtype = PyExc_SyntaxError;
1821 msg = "invalid syntax";
1822 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001823 break;
1824 case E_TOKEN:
1825 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001826 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001827 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001828 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001829 break;
1830 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001831 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001832 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001833 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001834 if (!PyErr_Occurred())
1835 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001836 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001837 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001838 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001839 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001840 case E_EOF:
1841 msg = "unexpected EOF while parsing";
1842 break;
Fred Drake85f36392000-07-11 17:53:00 +00001843 case E_TABSPACE:
1844 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001845 msg = "inconsistent use of tabs and spaces in indentation";
1846 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001847 case E_OVERFLOW:
1848 msg = "expression too long";
1849 break;
Fred Drake85f36392000-07-11 17:53:00 +00001850 case E_DEDENT:
1851 errtype = PyExc_IndentationError;
1852 msg = "unindent does not match any outer indentation level";
1853 break;
1854 case E_TOODEEP:
1855 errtype = PyExc_IndentationError;
1856 msg = "too many levels of indentation";
1857 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001858 case E_DECODE: {
1859 PyObject *type, *value, *tb;
1860 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001861 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001862 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001863 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001864 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001865 }
1866 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001867 if (msg == NULL)
1868 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001869 Py_XDECREF(type);
1870 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001871 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001872 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001873 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001874 case E_LINECONT:
1875 msg = "unexpected character after line continuation character";
1876 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001877
1878 case E_IDENTIFIER:
1879 msg = "invalid character in identifier";
1880 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001881 default:
1882 fprintf(stderr, "error=%d\n", err->error);
1883 msg = "unknown parsing error";
1884 break;
1885 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001886 /* err->text may not be UTF-8 in case of decoding errors.
1887 Explicitly convert to an object. */
1888 if (!err->text) {
1889 errtext = Py_None;
1890 Py_INCREF(Py_None);
1891 } else {
1892 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1893 "replace");
1894 }
1895 v = Py_BuildValue("(ziiN)", err->filename,
1896 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001897 w = NULL;
1898 if (v != NULL)
1899 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001900 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001901 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001902 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001903 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001904cleanup:
1905 if (err->text != NULL) {
1906 PyObject_FREE(err->text);
1907 err->text = NULL;
1908 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001909}
1910
1911/* Print fatal error message and abort */
1912
1913void
Tim Peters7c321a82002-07-09 02:57:01 +00001914Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001915{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001916 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001917 if (PyErr_Occurred()) {
1918 PyErr_Print();
1919 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001920#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001921 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001922 OutputDebugString(msg);
1923 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001924#ifdef _DEBUG
1925 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001926#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001927#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001928 abort();
1929}
1930
1931/* Clean up and exit */
1932
Guido van Rossuma110aa61994-08-29 12:50:44 +00001933#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001934#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001935#endif
1936
Collin Winter670e6922007-03-21 02:57:17 +00001937static void (*pyexitfunc)(void) = NULL;
1938/* For the atexit module. */
1939void _Py_PyAtExit(void (*func)(void))
1940{
1941 pyexitfunc = func;
1942}
1943
1944static void
1945call_py_exitfuncs(void)
1946{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001947 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00001948 return;
1949
1950 (*pyexitfunc)();
1951 PyErr_Clear();
1952}
1953
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001954#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001955static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001956static int nexitfuncs = 0;
1957
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001958int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001959{
1960 if (nexitfuncs >= NEXITFUNCS)
1961 return -1;
1962 exitfuncs[nexitfuncs++] = func;
1963 return 0;
1964}
1965
Guido van Rossumcc283f51997-08-05 02:22:03 +00001966static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001967call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001968{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001969 while (nexitfuncs > 0)
1970 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001971
1972 fflush(stdout);
1973 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001974}
1975
1976void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001977Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001978{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001979 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001980
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001981 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001982}
1983
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001984static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001985initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001986{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001987#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001988 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001989#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001990#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001991 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001992#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001993#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001994 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001995#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001996 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001997}
1998
Guido van Rossum7433b121997-02-14 19:45:36 +00001999
2000/*
2001 * The file descriptor fd is considered ``interactive'' if either
2002 * a) isatty(fd) is TRUE, or
2003 * b) the -i flag was given, and the filename associated with
2004 * the descriptor is NULL or "<stdin>" or "???".
2005 */
2006int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002007Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002008{
2009 if (isatty((int)fileno(fp)))
2010 return 1;
2011 if (!Py_InteractiveFlag)
2012 return 0;
2013 return (filename == NULL) ||
2014 (strcmp(filename, "<stdin>") == 0) ||
2015 (strcmp(filename, "???") == 0);
2016}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002017
2018
Tim Petersd08e3822003-04-17 15:24:21 +00002019#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002020#if defined(WIN32) && defined(_MSC_VER)
2021
2022/* Stack checking for Microsoft C */
2023
2024#include <malloc.h>
2025#include <excpt.h>
2026
Fred Drakee8de31c2000-08-31 05:38:39 +00002027/*
2028 * Return non-zero when we run out of memory on the stack; zero otherwise.
2029 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002030int
Fred Drake399739f2000-08-31 05:52:44 +00002031PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002032{
2033 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00002034 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002035 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00002036 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002037 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00002038 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00002039 EXCEPTION_EXECUTE_HANDLER :
2040 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00002041 int errcode = _resetstkoflw();
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +00002042 if (errcode == 0)
Christian Heimes7131fd92008-02-19 14:21:46 +00002043 {
2044 Py_FatalError("Could not reset the stack!");
2045 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002046 }
2047 return 1;
2048}
2049
2050#endif /* WIN32 && _MSC_VER */
2051
2052/* Alternate implementations can be added here... */
2053
2054#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002055
2056
2057/* Wrappers around sigaction() or signal(). */
2058
2059PyOS_sighandler_t
2060PyOS_getsig(int sig)
2061{
2062#ifdef HAVE_SIGACTION
2063 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002064 if (sigaction(sig, NULL, &context) == -1)
2065 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002066 return context.sa_handler;
2067#else
2068 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002069/* Special signal handling for the secure CRT in Visual Studio 2005 */
2070#if defined(_MSC_VER) && _MSC_VER >= 1400
2071 switch (sig) {
2072 /* Only these signals are valid */
2073 case SIGINT:
2074 case SIGILL:
2075 case SIGFPE:
2076 case SIGSEGV:
2077 case SIGTERM:
2078 case SIGBREAK:
2079 case SIGABRT:
2080 break;
2081 /* Don't call signal() with other values or it will assert */
2082 default:
2083 return SIG_ERR;
2084 }
2085#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002086 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002087 if (handler != SIG_ERR)
2088 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002089 return handler;
2090#endif
2091}
2092
2093PyOS_sighandler_t
2094PyOS_setsig(int sig, PyOS_sighandler_t handler)
2095{
2096#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002097 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002098 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002099 sigemptyset(&context.sa_mask);
2100 context.sa_flags = 0;
2101 if (sigaction(sig, &context, &ocontext) == -1)
2102 return SIG_ERR;
2103 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002104#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002105 PyOS_sighandler_t oldhandler;
2106 oldhandler = signal(sig, handler);
2107#ifdef HAVE_SIGINTERRUPT
2108 siginterrupt(sig, 1);
2109#endif
2110 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002111#endif
2112}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002113
2114/* Deprecated C API functions still provided for binary compatiblity */
2115
2116#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002117PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002118PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2119{
2120 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2121}
2122
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002123#undef PyParser_SimpleParseString
2124PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002125PyParser_SimpleParseString(const char *str, int start)
2126{
2127 return PyParser_SimpleParseStringFlags(str, start, 0);
2128}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002129
2130#undef PyRun_AnyFile
2131PyAPI_FUNC(int)
2132PyRun_AnyFile(FILE *fp, const char *name)
2133{
2134 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2135}
2136
2137#undef PyRun_AnyFileEx
2138PyAPI_FUNC(int)
2139PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2140{
2141 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2142}
2143
2144#undef PyRun_AnyFileFlags
2145PyAPI_FUNC(int)
2146PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2147{
2148 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2149}
2150
2151#undef PyRun_File
2152PyAPI_FUNC(PyObject *)
2153PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2154{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002155 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002156}
2157
2158#undef PyRun_FileEx
2159PyAPI_FUNC(PyObject *)
2160PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2161{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002162 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002163}
2164
2165#undef PyRun_FileFlags
2166PyAPI_FUNC(PyObject *)
2167PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2168 PyCompilerFlags *flags)
2169{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002170 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002171}
2172
2173#undef PyRun_SimpleFile
2174PyAPI_FUNC(int)
2175PyRun_SimpleFile(FILE *f, const char *p)
2176{
2177 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2178}
2179
2180#undef PyRun_SimpleFileEx
2181PyAPI_FUNC(int)
2182PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2183{
2184 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2185}
2186
2187
2188#undef PyRun_String
2189PyAPI_FUNC(PyObject *)
2190PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2191{
2192 return PyRun_StringFlags(str, s, g, l, NULL);
2193}
2194
2195#undef PyRun_SimpleString
2196PyAPI_FUNC(int)
2197PyRun_SimpleString(const char *s)
2198{
2199 return PyRun_SimpleStringFlags(s, NULL);
2200}
2201
2202#undef Py_CompileString
2203PyAPI_FUNC(PyObject *)
2204Py_CompileString(const char *str, const char *p, int s)
2205{
2206 return Py_CompileStringFlags(str, p, s, NULL);
2207}
2208
2209#undef PyRun_InteractiveOne
2210PyAPI_FUNC(int)
2211PyRun_InteractiveOne(FILE *f, const char *p)
2212{
2213 return PyRun_InteractiveOneFlags(f, p, NULL);
2214}
2215
2216#undef PyRun_InteractiveLoop
2217PyAPI_FUNC(int)
2218PyRun_InteractiveLoop(FILE *f, const char *p)
2219{
2220 return PyRun_InteractiveLoopFlags(f, p, NULL);
2221}
2222
2223#ifdef __cplusplus
2224}
2225#endif