blob: a3cce33bed71de12511ac7048e6f7b955a77cb3f [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öwis5c88d812009-01-02 20:47:48 +000026#include "malloc.h" /* for alloca */
27
Martin v. Löwis73d538b2003-03-05 15:13:47 +000028#ifdef HAVE_LANGINFO_H
29#include <locale.h>
30#include <langinfo.h>
31#endif
32
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000033#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000034#undef BYTE
35#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000036#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000037#endif
38
Neal Norwitz4281cef2006-03-04 19:58:13 +000039#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000040#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000041#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000042#define PRINT_TOTAL_REFS() fprintf(stderr, \
43 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
44 _Py_GetRefTotal())
45#endif
46
47#ifdef __cplusplus
48extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000049#endif
50
Martin v. Löwis790465f2008-04-05 20:41:37 +000051extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000052
Guido van Rossum82598051997-03-05 00:20:32 +000053extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000054
Guido van Rossumb73cc041993-11-01 16:28:59 +000055/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000056static void initmain(void);
57static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
65static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000066static void call_py_exitfuncs(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000067static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000068extern void _PyUnicode_Init(void);
69extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000070extern int _PyLong_Init(void);
71extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000072
Mark Hammond8d98d2c2003-04-19 15:41:53 +000073#ifdef WITH_THREAD
74extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
75extern void _PyGILState_Fini(void);
76#endif /* WITH_THREAD */
77
Guido van Rossum82598051997-03-05 00:20:32 +000078int Py_DebugFlag; /* Needed by parser.c */
79int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000080int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000081int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000082int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000083int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000084int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000085int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000086int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000087int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000088int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000089
Christian Heimes33fe8092008-04-13 13:53:33 +000090/* PyModule_GetWarningsModule is no longer necessary as of 2.6
91since _warnings is builtin. This API should not be used. */
92PyObject *
93PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000094{
Christian Heimes33fe8092008-04-13 13:53:33 +000095 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000096}
Mark Hammonda43fd0c2003-02-19 00:33:33 +000097
Guido van Rossum25ce5661997-08-02 03:10:38 +000098static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000099
Thomas Wouters7e474022000-07-16 12:04:32 +0000100/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000101
102int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000103Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000104{
105 return initialized;
106}
107
Guido van Rossum25ce5661997-08-02 03:10:38 +0000108/* Global initializations. Can be undone by Py_Finalize(). Don't
109 call this twice without an intervening Py_Finalize() call. When
110 initializations fail, a fatal error is issued and the function does
111 not return. On return, the first thread and interpreter state have
112 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000113
Guido van Rossum25ce5661997-08-02 03:10:38 +0000114 Locking: you must hold the interpreter lock while calling this.
115 (If the lock has not yet been initialized, that's equivalent to
116 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000117
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000119
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000120static int
121add_flag(int flag, const char *envs)
122{
123 int env = atoi(envs);
124 if (flag < env)
125 flag = env;
126 if (flag < 1)
127 flag = 1;
128 return flag;
129}
130
Christian Heimes5833a2f2008-10-30 21:40:04 +0000131#if defined(HAVE_LANGINFO_H) && defined(CODESET)
132static char*
133get_codeset(void)
134{
135 char* codeset;
136 PyObject *codec, *name;
137
138 codeset = nl_langinfo(CODESET);
139 if (!codeset || codeset[0] == '\0')
140 return NULL;
141
142 codec = _PyCodec_Lookup(codeset);
143 if (!codec)
144 goto error;
145
146 name = PyObject_GetAttrString(codec, "name");
147 Py_CLEAR(codec);
148 if (!name)
149 goto error;
150
151 codeset = strdup(_PyUnicode_AsString(name));
152 Py_DECREF(name);
153 return codeset;
154
155error:
156 Py_XDECREF(codec);
157 PyErr_Clear();
158 return NULL;
159}
160#endif
161
Guido van Rossuma027efa1997-05-05 20:56:21 +0000162void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000163Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000164{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000165 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000166 PyThreadState *tstate;
Guido van Rossum826d8972007-10-30 18:34:07 +0000167 PyObject *bimod, *sysmod, *pstderr;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000168 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000169#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000170 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000171#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000172 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000173
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000174 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000175 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000176 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000177
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000178#ifdef HAVE_SETLOCALE
179 /* Set up the LC_CTYPE locale, so we can obtain
180 the locale's charset without having to switch
181 locales. */
182 setlocale(LC_CTYPE, "");
183#endif
184
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000185 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000186 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000187 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000188 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000189 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000190 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Christian Heimes790c8232008-01-07 21:14:23 +0000191 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
192 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000193
Guido van Rossuma027efa1997-05-05 20:56:21 +0000194 interp = PyInterpreterState_New();
195 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000196 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000197
Guido van Rossuma027efa1997-05-05 20:56:21 +0000198 tstate = PyThreadState_New(interp);
199 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000200 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000201 (void) PyThreadState_Swap(tstate);
202
Guido van Rossum70d893a2001-08-16 08:21:42 +0000203 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000204
Neal Norwitzb2501f42002-12-31 03:42:13 +0000205 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000206 Py_FatalError("Py_Initialize: can't init frames");
207
Guido van Rossumddefaf32007-01-14 03:31:43 +0000208 if (!_PyLong_Init())
209 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000210
Christian Heimes9c4756e2008-05-26 13:22:05 +0000211 if (!PyByteArray_Init())
Neal Norwitz6968b052007-02-27 19:02:19 +0000212 Py_FatalError("Py_Initialize: can't init bytes");
213
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000214 _PyFloat_Init();
215
Guido van Rossum25ce5661997-08-02 03:10:38 +0000216 interp->modules = PyDict_New();
217 if (interp->modules == NULL)
218 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000219 interp->modules_reloading = PyDict_New();
220 if (interp->modules_reloading == NULL)
221 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000222
Guido van Rossumc94044c2000-03-10 23:03:54 +0000223 /* Init Unicode implementation; relies on the codec registry */
224 _PyUnicode_Init();
225
Barry Warsawf242aa02000-05-25 23:09:49 +0000226 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000227 if (bimod == NULL)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000228 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Martin v. Löwis1a214512008-06-11 05:26:20 +0000229 _PyImport_FixupExtension(bimod, "builtins", "builtins");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000230 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000231 if (interp->builtins == NULL)
232 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000233 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000234
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000235 /* initialize builtin exceptions */
236 _PyExc_Init();
237
Guido van Rossum25ce5661997-08-02 03:10:38 +0000238 sysmod = _PySys_Init();
239 if (sysmod == NULL)
240 Py_FatalError("Py_Initialize: can't initialize sys");
241 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000242 if (interp->sysdict == NULL)
243 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000244 Py_INCREF(interp->sysdict);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000245 _PyImport_FixupExtension(sysmod, "sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000246 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000247 PyDict_SetItemString(interp->sysdict, "modules",
248 interp->modules);
249
Guido van Rossum826d8972007-10-30 18:34:07 +0000250 /* Set up a preliminary stderr printer until we have enough
251 infrastructure for the io module in place. */
252 pstderr = PyFile_NewStdPrinter(fileno(stderr));
253 if (pstderr == NULL)
254 Py_FatalError("Py_Initialize: can't set preliminary stderr");
255 PySys_SetObject("stderr", pstderr);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000256 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000257
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000258 _PyImport_Init();
259
Just van Rossum52e14d62002-12-30 22:08:05 +0000260 _PyImportHooks_Init();
261
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000262 if (install_sigs)
263 initsigs(); /* Signal handling stuff, including initintr() */
Christian Heimes33fe8092008-04-13 13:53:33 +0000264
Georg Brandl86b2fb92008-07-16 03:43:04 +0000265 /* Initialize warnings. */
266 _PyWarnings_Init();
267 if (PySys_HasWarnOptions()) {
268 PyObject *warnings_module = PyImport_ImportModule("warnings");
269 if (!warnings_module)
270 PyErr_Clear();
271 Py_XDECREF(warnings_module);
272 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000273
274 initmain(); /* Module __main__ */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000275 if (initstdio() < 0)
276 Py_FatalError(
277 "Py_Initialize: can't initialize sys standard streams");
Benjamin Peterson791dc2f2008-09-05 23:27:15 +0000278 if (!Py_NoSiteFlag)
279 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000280
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000281 /* auto-thread-state API, if available */
282#ifdef WITH_THREAD
283 _PyGILState_Init(interp, tstate);
284#endif /* WITH_THREAD */
285
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000286#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000287 /* On Unix, set the file system encoding according to the
288 user's preference, if the CODESET names a well-known
289 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000290 initialized by other means. Also set the encoding of
291 stdin and stdout if these are terminals. */
292
Christian Heimes5833a2f2008-10-30 21:40:04 +0000293 codeset = get_codeset();
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000294 if (codeset) {
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000295 if (!Py_FileSystemDefaultEncoding)
296 Py_FileSystemDefaultEncoding = codeset;
297 else
298 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000299 }
300#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000301}
302
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000303void
304Py_Initialize(void)
305{
306 Py_InitializeEx(1);
307}
308
309
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000310#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000311extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000312#endif
313
Guido van Rossume8432ac2007-07-09 15:04:50 +0000314/* Flush stdout and stderr */
315
Neal Norwitz2bad9702007-08-27 06:19:22 +0000316static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000317flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000318{
319 PyObject *fout = PySys_GetObject("stdout");
320 PyObject *ferr = PySys_GetObject("stderr");
321 PyObject *tmp;
322
Christian Heimes2be03732007-11-15 02:26:46 +0000323 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000324 tmp = PyObject_CallMethod(fout, "flush", "");
325 if (tmp == NULL)
326 PyErr_Clear();
327 else
328 Py_DECREF(tmp);
329 }
330
Christian Heimes2be03732007-11-15 02:26:46 +0000331 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000332 tmp = PyObject_CallMethod(ferr, "flush", "");
333 if (tmp == NULL)
334 PyErr_Clear();
335 else
336 Py_DECREF(tmp);
337 }
338}
339
Guido van Rossum25ce5661997-08-02 03:10:38 +0000340/* Undo the effect of Py_Initialize().
341
342 Beware: if multiple interpreter and/or thread states exist, these
343 are not wiped out; only the current thread and interpreter state
344 are deleted. But since everything else is deleted, those other
345 interpreter and thread states should no longer be used.
346
347 (XXX We should do better, e.g. wipe out all interpreters and
348 threads.)
349
350 Locking: as above.
351
352*/
353
354void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000355Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000356{
357 PyInterpreterState *interp;
358 PyThreadState *tstate;
359
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000360 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000361 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362
Tim Peters384fd102001-01-21 03:40:37 +0000363 /* The interpreter is still entirely intact at this point, and the
364 * exit funcs may be relying on that. In particular, if some thread
365 * or exit func is still waiting to do an import, the import machinery
366 * expects Py_IsInitialized() to return true. So don't say the
367 * interpreter is uninitialized until after the exit funcs have run.
368 * Note that Threading.py uses an exit func to do a join on all the
369 * threads created thru it, so this also protects pending imports in
370 * the threads created via Threading.
371 */
Collin Winter670e6922007-03-21 02:57:17 +0000372 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000373 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000374
Guido van Rossume8432ac2007-07-09 15:04:50 +0000375 /* Flush stdout+stderr */
376 flush_std_files();
377
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000378 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000379 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380 interp = tstate->interp;
381
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000382 /* Disable signal handling */
383 PyOS_FiniInterrupts();
384
Christian Heimes26855632008-01-27 23:50:43 +0000385 /* Clear type lookup cache */
386 PyType_ClearCache();
387
Guido van Rossume13ddc92003-04-17 17:29:22 +0000388 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000389 * before all modules are destroyed.
390 * XXX If a __del__ or weakref callback is triggered here, and tries to
391 * XXX import a module, bad things can happen, because Python no
392 * XXX longer believes it's initialized.
393 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
394 * XXX is easy to provoke that way. I've also seen, e.g.,
395 * XXX Exception exceptions.ImportError: 'No module named sha'
396 * XXX in <function callback at 0x008F5718> ignored
397 * XXX but I'm unclear on exactly how that one happens. In any case,
398 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000399 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000400 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000401#ifdef COUNT_ALLOCS
402 /* With COUNT_ALLOCS, it helps to run GC multiple times:
403 each collection might release some types from the type
404 list, so they become garbage. */
405 while (PyGC_Collect() > 0)
406 /* nothing */;
407#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000408
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000409 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000410 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000411
Guido van Rossume8432ac2007-07-09 15:04:50 +0000412 /* Flush stdout+stderr (again, in case more was printed) */
413 flush_std_files();
414
Guido van Rossume13ddc92003-04-17 17:29:22 +0000415 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000416 * new-style class definitions, for example.
417 * XXX This is disabled because it caused too many problems. If
418 * XXX a __del__ or weakref callback triggers here, Python code has
419 * XXX a hard time running, because even the sys module has been
420 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
421 * XXX One symptom is a sequence of information-free messages
422 * XXX coming from threads (if a __del__ or callback is invoked,
423 * XXX other threads can execute too, and any exception they encounter
424 * XXX triggers a comedy of errors as subsystem after subsystem
425 * XXX fails to find what it *expects* to find in sys to help report
426 * XXX the exception and consequent unexpected failures). I've also
427 * XXX seen segfaults then, after adding print statements to the
428 * XXX Python code getting called.
429 */
430#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000431 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000432#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000433
Guido van Rossum1707aad1997-12-08 23:43:45 +0000434 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
435 _PyImport_Fini();
436
437 /* Debugging stuff */
438#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000439 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000440#endif
441
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000442 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000443
Tim Peters9cf25ce2003-04-17 15:21:01 +0000444#ifdef Py_TRACE_REFS
445 /* Display all objects still alive -- this can invoke arbitrary
446 * __repr__ overrides, so requires a mostly-intact interpreter.
447 * Alas, a lot of stuff may still be alive now that will be cleaned
448 * up later.
449 */
Tim Peters269b2a62003-04-17 19:52:29 +0000450 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000451 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000452#endif /* Py_TRACE_REFS */
453
Guido van Rossumd922fa42003-04-15 14:10:09 +0000454 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000455 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000456
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000457 /* Now we decref the exception classes. After this point nothing
458 can raise an exception. That's okay, because each Fini() method
459 below has been checked to make sure no exceptions are ever
460 raised.
461 */
462
463 _PyExc_Fini();
464
Christian Heimes7d2ff882007-11-30 14:35:04 +0000465 /* Cleanup auto-thread-state */
466#ifdef WITH_THREAD
467 _PyGILState_Fini();
468#endif /* WITH_THREAD */
469
Guido van Rossumd922fa42003-04-15 14:10:09 +0000470 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000471 PyThreadState_Swap(NULL);
472 PyInterpreterState_Delete(interp);
473
Guido van Rossumd922fa42003-04-15 14:10:09 +0000474 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000475 PyMethod_Fini();
476 PyFrame_Fini();
477 PyCFunction_Fini();
478 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000479 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000480 PySet_Fini();
Christian Heimes72b710a2008-05-26 13:28:38 +0000481 PyBytes_Fini();
Christian Heimes9c4756e2008-05-26 13:22:05 +0000482 PyByteArray_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000483 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000484 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000485 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000486
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000487 /* Cleanup Unicode implementation */
488 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000489
Christian Heimesc8967002007-11-30 10:18:26 +0000490 /* reset file system default encoding */
491 if (!Py_HasFileSystemDefaultEncoding) {
492 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000493 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000494 }
495
Guido van Rossumcc283f51997-08-05 02:22:03 +0000496 /* XXX Still allocated:
497 - various static ad-hoc pointers to interned strings
498 - int and float free list blocks
499 - whatever various modules and libraries allocate
500 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000501
502 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000503
Tim Peters269b2a62003-04-17 19:52:29 +0000504#ifdef Py_TRACE_REFS
505 /* Display addresses (& refcnts) of all objects still alive.
506 * An address can be used to find the repr of the object, printed
507 * above by _Py_PrintReferences.
508 */
509 if (Py_GETENV("PYTHONDUMPREFS"))
510 _Py_PrintReferenceAddresses(stderr);
511#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000512#ifdef PYMALLOC_DEBUG
513 if (Py_GETENV("PYTHONMALLOCSTATS"))
514 _PyObject_DebugMallocStats();
515#endif
516
Guido van Rossumcc283f51997-08-05 02:22:03 +0000517 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000518}
519
520/* Create and initialize a new interpreter and thread, and return the
521 new thread. This requires that Py_Initialize() has been called
522 first.
523
524 Unsuccessful initialization yields a NULL pointer. Note that *no*
525 exception information is available even in this case -- the
526 exception information is held in the thread, and there is no
527 thread.
528
529 Locking: as above.
530
531*/
532
533PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000534Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000535{
536 PyInterpreterState *interp;
537 PyThreadState *tstate, *save_tstate;
538 PyObject *bimod, *sysmod;
539
540 if (!initialized)
541 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
542
543 interp = PyInterpreterState_New();
544 if (interp == NULL)
545 return NULL;
546
547 tstate = PyThreadState_New(interp);
548 if (tstate == NULL) {
549 PyInterpreterState_Delete(interp);
550 return NULL;
551 }
552
553 save_tstate = PyThreadState_Swap(tstate);
554
555 /* XXX The following is lax in error checking */
556
557 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000558 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Georg Brandl1a3284e2007-12-02 09:40:06 +0000560 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000562 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000563 if (interp->builtins == NULL)
564 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000565 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000567
568 /* initialize builtin exceptions */
569 _PyExc_Init();
570
Guido van Rossum25ce5661997-08-02 03:10:38 +0000571 sysmod = _PyImport_FindExtension("sys", "sys");
572 if (bimod != NULL && sysmod != NULL) {
Christian Heimes6a27efa2008-10-30 21:48:26 +0000573 PyObject *pstderr;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000575 if (interp->sysdict == NULL)
576 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577 Py_INCREF(interp->sysdict);
578 PySys_SetPath(Py_GetPath());
579 PyDict_SetItemString(interp->sysdict, "modules",
580 interp->modules);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000581 /* Set up a preliminary stderr printer until we have enough
582 infrastructure for the io module in place. */
583 pstderr = PyFile_NewStdPrinter(fileno(stderr));
584 if (pstderr == NULL)
585 Py_FatalError("Py_Initialize: can't set preliminary stderr");
586 PySys_SetObject("stderr", pstderr);
587 PySys_SetObject("__stderr__", pstderr);
588
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000589 _PyImportHooks_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000590 if (initstdio() < 0)
591 Py_FatalError(
592 "Py_Initialize: can't initialize sys standard streams");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000593 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000594 if (!Py_NoSiteFlag)
595 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596 }
597
598 if (!PyErr_Occurred())
599 return tstate;
600
Thomas Wouters89f507f2006-12-13 04:49:30 +0000601handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000602 /* Oops, it didn't work. Undo it all. */
603
604 PyErr_Print();
605 PyThreadState_Clear(tstate);
606 PyThreadState_Swap(save_tstate);
607 PyThreadState_Delete(tstate);
608 PyInterpreterState_Delete(interp);
609
610 return NULL;
611}
612
613/* Delete an interpreter and its last thread. This requires that the
614 given thread state is current, that the thread has no remaining
615 frames, and that it is its interpreter's only remaining thread.
616 It is a fatal error to violate these constraints.
617
618 (Py_Finalize() doesn't have these constraints -- it zaps
619 everything, regardless.)
620
621 Locking: as above.
622
623*/
624
625void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000626Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000627{
628 PyInterpreterState *interp = tstate->interp;
629
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000630 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631 Py_FatalError("Py_EndInterpreter: thread is not current");
632 if (tstate->frame != NULL)
633 Py_FatalError("Py_EndInterpreter: thread still has a frame");
634 if (tstate != interp->tstate_head || tstate->next != NULL)
635 Py_FatalError("Py_EndInterpreter: not the last thread");
636
637 PyImport_Cleanup();
638 PyInterpreterState_Clear(interp);
639 PyThreadState_Swap(NULL);
640 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000641}
642
Martin v. Löwis790465f2008-04-05 20:41:37 +0000643static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000644
645void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000646Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000647{
648 if (pn && *pn)
649 progname = pn;
650}
651
Martin v. Löwis790465f2008-04-05 20:41:37 +0000652wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000653Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000654{
655 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000656}
657
Martin v. Löwis790465f2008-04-05 20:41:37 +0000658static wchar_t *default_home = NULL;
659static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000660
661void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000662Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000663{
664 default_home = home;
665}
666
Martin v. Löwis790465f2008-04-05 20:41:37 +0000667wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000668Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000669{
Martin v. Löwis790465f2008-04-05 20:41:37 +0000670 wchar_t *home = default_home;
671 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
672 char* chome = Py_GETENV("PYTHONHOME");
673 if (chome) {
674 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
675 if (r != (size_t)-1 && r <= PATH_MAX)
676 home = env_home;
677 }
678
679 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000680 return home;
681}
682
Guido van Rossum6135a871995-01-09 17:53:26 +0000683/* Create __main__ module */
684
685static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000686initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000687{
Guido van Rossum82598051997-03-05 00:20:32 +0000688 PyObject *m, *d;
689 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000690 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000691 Py_FatalError("can't create __main__ module");
692 d = PyModule_GetDict(m);
693 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000694 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000695 if (bimod == NULL ||
696 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000697 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000698 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000699 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000700}
701
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000702/* Import the site module (not into __main__ though) */
703
704static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000705initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000706{
707 PyObject *m, *f;
708 m = PyImport_ImportModule("site");
709 if (m == NULL) {
710 f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +0000711 if (f == NULL || f == Py_None)
712 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000713 if (Py_VerboseFlag) {
714 PyFile_WriteString(
715 "'import site' failed; traceback:\n", f);
716 PyErr_Print();
717 }
718 else {
719 PyFile_WriteString(
720 "'import site' failed; use -v for traceback\n", f);
721 PyErr_Clear();
722 }
723 }
724 else {
725 Py_DECREF(m);
726 }
727}
728
Georg Brandl1a3284e2007-12-02 09:40:06 +0000729/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000730static int
731initstdio(void)
732{
733 PyObject *iomod = NULL, *wrapper;
734 PyObject *bimod = NULL;
735 PyObject *m;
736 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000737 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000738 PyObject * encoding_attr;
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +0000739 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000740
741 /* Hack to avoid a nasty recursion issue when Python is invoked
742 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
743 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
744 goto error;
745 }
746 Py_DECREF(m);
747
748 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
749 goto error;
750 }
751 Py_DECREF(m);
752
Georg Brandl1a3284e2007-12-02 09:40:06 +0000753 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000754 goto error;
755 }
756
757 if (!(iomod = PyImport_ImportModule("io"))) {
758 goto error;
759 }
760 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
761 goto error;
762 }
763
Georg Brandl1a3284e2007-12-02 09:40:06 +0000764 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000765 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
766 goto error;
767 }
768
Martin v. Löwis0f599892008-06-02 11:13:03 +0000769 encoding = Py_GETENV("PYTHONIOENCODING");
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000770 errors = NULL;
Martin v. Löwis0f599892008-06-02 11:13:03 +0000771 if (encoding) {
772 encoding = strdup(encoding);
773 errors = strchr(encoding, ':');
774 if (errors) {
775 *errors = '\0';
776 errors++;
777 }
778 }
779
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000780 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000781 fd = fileno(stdin);
782 /* Under some conditions stdin, stdout and stderr may not be connected
783 * and fileno() may point to an invalid file descriptor. For example
784 * GUI apps don't have valid standard streams by default.
785 */
786 if (fd < 0) {
787#ifdef MS_WINDOWS
788 std = Py_None;
789 Py_INCREF(std);
790#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000791 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000792#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000793 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000794 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000795 if (!(std = PyFile_FromFd(fd, "<stdin>", "r", -1, encoding,
796 errors, "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000797 goto error;
798 }
799 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000800 PySys_SetObject("__stdin__", std);
801 PySys_SetObject("stdin", std);
802 Py_DECREF(std);
803
804 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000805 fd = fileno(stdout);
806 if (fd < 0) {
807#ifdef MS_WINDOWS
808 std = Py_None;
809 Py_INCREF(std);
810#else
811 goto error;
812#endif
813 }
814 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000815 if (!(std = PyFile_FromFd(fd, "<stdout>", "w", -1, encoding,
816 errors, "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000817 goto error;
818 }
819 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000820 PySys_SetObject("__stdout__", std);
821 PySys_SetObject("stdout", std);
822 Py_DECREF(std);
823
Guido van Rossum98297ee2007-11-06 21:34:58 +0000824#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000825 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000826 fd = fileno(stderr);
827 if (fd < 0) {
828#ifdef MS_WINDOWS
829 std = Py_None;
830 Py_INCREF(std);
831#else
832 goto error;
833#endif
834 }
835 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000836 if (!(std = PyFile_FromFd(fd, "<stderr>", "w", -1, encoding,
Georg Brandl559e5d72008-06-11 18:37:52 +0000837 "backslashreplace", "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000838 goto error;
839 }
840 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000841
842 /* Same as hack above, pre-import stderr's codec to avoid recursion
843 when import.c tries to write to stderr in verbose mode. */
844 encoding_attr = PyObject_GetAttrString(std, "encoding");
845 if (encoding_attr != NULL) {
846 const char * encoding;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000847 encoding = _PyUnicode_AsString(encoding_attr);
Trent Nelson39e307e2008-03-19 06:45:48 +0000848 if (encoding != NULL) {
849 _PyCodec_Lookup(encoding);
850 }
851 }
852 PyErr_Clear(); /* Not a fatal error if codec isn't available */
853
Christian Heimesdb233082007-11-13 02:34:21 +0000854 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000855 PySys_SetObject("stderr", std);
856 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000857#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000858
Christian Heimes58cb1b82007-11-13 02:19:40 +0000859 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000860 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000861 status = -1;
862 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000863
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000864 if (encoding)
865 free(encoding);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000866 Py_XDECREF(bimod);
867 Py_XDECREF(iomod);
868 return status;
869}
870
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000871/* Parse input from a file and execute it */
872
873int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000874PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000875 PyCompilerFlags *flags)
876{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000877 if (filename == NULL)
878 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000879 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000880 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000881 if (closeit)
882 fclose(fp);
883 return err;
884 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000885 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000886 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000887}
888
889int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000890PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000891{
Guido van Rossum82598051997-03-05 00:20:32 +0000892 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000893 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000894 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000895
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000896 if (flags == NULL) {
897 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000898 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000899 }
Guido van Rossum82598051997-03-05 00:20:32 +0000900 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000901 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000902 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000903 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000904 }
Guido van Rossum82598051997-03-05 00:20:32 +0000905 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000906 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000907 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000908 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000909 }
910 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000911 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000912 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000913 if (ret == E_EOF)
914 return 0;
915 /*
916 if (ret == E_NOMEM)
917 return -1;
918 */
919 }
920}
921
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000922/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000923#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000924 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Guido van Rossum45aecf42006-03-15 04:58:47 +0000925 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000926
Thomas Wouters89f507f2006-12-13 04:49:30 +0000927#if 0
928/* Keep an example of flags with future keyword support. */
929#define PARSER_FLAGS(flags) \
930 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
931 PyPARSE_DONT_IMPLY_DEDENT : 0) \
932 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
933 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
934#endif
935
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000936int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000937PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000938{
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000939 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000940 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +0000941 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000942 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000943 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000944
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000945 if (fp == stdin) {
946 /* Fetch encoding from sys.stdin */
947 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +0000948 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000949 return -1;
950 oenc = PyObject_GetAttrString(v, "encoding");
951 if (!oenc)
952 return -1;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000953 enc = _PyUnicode_AsString(oenc);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000954 }
Guido van Rossum82598051997-03-05 00:20:32 +0000955 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000956 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000957 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000958 if (v == NULL)
959 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000960 else if (PyUnicode_Check(v))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000961 ps1 = _PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000962 }
Guido van Rossum82598051997-03-05 00:20:32 +0000963 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000964 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000965 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000966 if (w == NULL)
967 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000968 else if (PyUnicode_Check(w))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000969 ps2 = _PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000970 }
Neal Norwitz9589ee22006-03-04 19:01:22 +0000971 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000972 if (arena == NULL) {
973 Py_XDECREF(v);
974 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000975 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000976 return -1;
977 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000978 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000980 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +0000981 Py_XDECREF(v);
982 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000983 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000984 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000985 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986 if (errcode == E_EOF) {
987 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000988 return E_EOF;
989 }
Guido van Rossum82598051997-03-05 00:20:32 +0000990 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000991 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000992 }
Guido van Rossum82598051997-03-05 00:20:32 +0000993 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000994 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000995 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000996 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000997 }
Guido van Rossum82598051997-03-05 00:20:32 +0000998 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000999 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001000 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001001 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001002 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001003 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001004 return -1;
1005 }
Guido van Rossum82598051997-03-05 00:20:32 +00001006 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001007 return 0;
1008}
1009
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001010/* Check whether a file maybe a pyc file: Look at the extension,
1011 the file type, and, if we may close it, at the first few bytes. */
1012
1013static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001014maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001015{
1016 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1017 return 1;
1018
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001019 /* Only look into the file if we are allowed to close it, since
1020 it then should also be seekable. */
1021 if (closeit) {
1022 /* Read only two bytes of the magic. If the file was opened in
1023 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1024 be read as they are on disk. */
1025 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1026 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001027 /* Mess: In case of -x, the stream is NOT at its start now,
1028 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001029 which makes the current stream position formally undefined,
1030 and a x-platform nightmare.
1031 Unfortunately, we have no direct way to know whether -x
1032 was specified. So we use a terrible hack: if the current
1033 stream position is not 0, we assume -x was specified, and
1034 give up. Bug 132850 on SourceForge spells out the
1035 hopelessness of trying anything else (fseek and ftell
1036 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001037 */
Tim Peters3e876562001-02-11 04:35:39 +00001038 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001039 if (ftell(fp) == 0) {
1040 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001041 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001042 ispyc = 1;
1043 rewind(fp);
1044 }
Tim Peters3e876562001-02-11 04:35:39 +00001045 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001046 }
1047 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001048}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001049
Guido van Rossum0df002c2000-08-27 19:21:52 +00001050int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001051PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001052 PyCompilerFlags *flags)
1053{
Guido van Rossum82598051997-03-05 00:20:32 +00001054 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001055 const char *ext;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001056 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001057
Guido van Rossum82598051997-03-05 00:20:32 +00001058 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001059 if (m == NULL)
1060 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001061 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001062 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001063 PyObject *f;
1064 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001065 if (f == NULL)
1066 return -1;
1067 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1068 Py_DECREF(f);
1069 return -1;
1070 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001071 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001072 Py_DECREF(f);
1073 }
Guido van Rossumfdef2711994-09-14 13:31:04 +00001074 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001075 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001076 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001077 if (closeit)
1078 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001079 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001080 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001081 ret = -1;
1082 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001083 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001084 /* Turn on optimization if a .pyo file is given */
1085 if (strcmp(ext, ".pyo") == 0)
1086 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001087 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001088 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001089 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001090 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001091 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001092 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001093 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001094 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001095 ret = -1;
1096 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001097 }
Guido van Rossum82598051997-03-05 00:20:32 +00001098 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001099 ret = 0;
1100 done:
1101 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1102 PyErr_Clear();
1103 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001104}
1105
1106int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001107PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001108{
Guido van Rossum82598051997-03-05 00:20:32 +00001109 PyObject *m, *d, *v;
1110 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001111 if (m == NULL)
1112 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001113 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001114 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001115 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001116 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001117 return -1;
1118 }
Guido van Rossum82598051997-03-05 00:20:32 +00001119 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001120 return 0;
1121}
1122
Barry Warsaw035574d1997-08-29 22:07:17 +00001123static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001124parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1125 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001126{
1127 long hold;
1128 PyObject *v;
1129
1130 /* old style errors */
1131 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001132 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001133 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001134
1135 /* new style errors. `err' is an instance */
1136
1137 if (! (v = PyObject_GetAttrString(err, "msg")))
1138 goto finally;
1139 *message = v;
1140
1141 if (!(v = PyObject_GetAttrString(err, "filename")))
1142 goto finally;
1143 if (v == Py_None)
1144 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001145 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001146 goto finally;
1147
1148 Py_DECREF(v);
1149 if (!(v = PyObject_GetAttrString(err, "lineno")))
1150 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001151 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001152 Py_DECREF(v);
1153 v = NULL;
1154 if (hold < 0 && PyErr_Occurred())
1155 goto finally;
1156 *lineno = (int)hold;
1157
1158 if (!(v = PyObject_GetAttrString(err, "offset")))
1159 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001160 if (v == Py_None) {
1161 *offset = -1;
1162 Py_DECREF(v);
1163 v = NULL;
1164 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001165 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001166 Py_DECREF(v);
1167 v = NULL;
1168 if (hold < 0 && PyErr_Occurred())
1169 goto finally;
1170 *offset = (int)hold;
1171 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001172
1173 if (!(v = PyObject_GetAttrString(err, "text")))
1174 goto finally;
1175 if (v == Py_None)
1176 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001177 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001178 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001179 goto finally;
1180 Py_DECREF(v);
1181 return 1;
1182
1183finally:
1184 Py_XDECREF(v);
1185 return 0;
1186}
1187
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001188void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001189PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001190{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001191 PyErr_PrintEx(1);
1192}
1193
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001194static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001195print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001196{
1197 char *nl;
1198 if (offset >= 0) {
1199 if (offset > 0 && offset == (int)strlen(text))
1200 offset--;
1201 for (;;) {
1202 nl = strchr(text, '\n');
1203 if (nl == NULL || nl-text >= offset)
1204 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001205 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001206 text = nl+1;
1207 }
1208 while (*text == ' ' || *text == '\t') {
1209 text++;
1210 offset--;
1211 }
1212 }
1213 PyFile_WriteString(" ", f);
1214 PyFile_WriteString(text, f);
1215 if (*text == '\0' || text[strlen(text)-1] != '\n')
1216 PyFile_WriteString("\n", f);
1217 if (offset == -1)
1218 return;
1219 PyFile_WriteString(" ", f);
1220 offset--;
1221 while (offset > 0) {
1222 PyFile_WriteString(" ", f);
1223 offset--;
1224 }
1225 PyFile_WriteString("^\n", f);
1226}
1227
Guido van Rossum66e8e862001-03-23 17:54:43 +00001228static void
1229handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001230{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001231 PyObject *exception, *value, *tb;
1232 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001233
Guido van Rossumd8faa362007-04-27 19:54:29 +00001234 if (Py_InspectFlag)
1235 /* Don't exit if -i flag was given. This flag is set to 0
1236 * when entering interactive mode for inspecting. */
1237 return;
1238
Guido van Rossum66e8e862001-03-23 17:54:43 +00001239 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001240 fflush(stdout);
1241 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001242 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001243 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001244 /* The error code should be in the `code' attribute. */
1245 PyObject *code = PyObject_GetAttrString(value, "code");
1246 if (code) {
1247 Py_DECREF(value);
1248 value = code;
1249 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001250 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001251 }
1252 /* If we failed to dig out the 'code' attribute,
1253 just let the else clause below print the error. */
1254 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001255 if (PyLong_Check(value))
1256 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001257 else {
1258 PyObject_Print(value, stderr, Py_PRINT_RAW);
1259 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001260 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001261 }
Tim Peterscf615b52003-04-19 18:47:02 +00001262 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001263 /* Restore and clear the exception info, in order to properly decref
1264 * the exception, value, and traceback. If we just exit instead,
1265 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1266 * some finalizers from running.
1267 */
Tim Peterscf615b52003-04-19 18:47:02 +00001268 PyErr_Restore(exception, value, tb);
1269 PyErr_Clear();
1270 Py_Exit(exitcode);
1271 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001272}
1273
1274void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001275PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001276{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001277 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001278
1279 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1280 handle_system_exit();
1281 }
Guido van Rossum82598051997-03-05 00:20:32 +00001282 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001283 if (exception == NULL)
1284 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001285 PyErr_NormalizeException(&exception, &v, &tb);
Antoine Pitroue2dffc02008-08-26 22:02:58 +00001286 if (tb == NULL) {
1287 tb = Py_None;
1288 Py_INCREF(tb);
1289 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001290 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001291 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001292 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001293 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001294 if (set_sys_last_vars) {
1295 PySys_SetObject("last_type", exception);
1296 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001297 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001298 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001299 hook = PySys_GetObject("excepthook");
1300 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001301 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001302 PyObject *result = PyEval_CallObject(hook, args);
1303 if (result == NULL) {
1304 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001305 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1306 handle_system_exit();
1307 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001308 PyErr_Fetch(&exception2, &v2, &tb2);
1309 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001310 /* It should not be possible for exception2 or v2
1311 to be NULL. However PyErr_Display() can't
1312 tolerate NULLs, so just be safe. */
1313 if (exception2 == NULL) {
1314 exception2 = Py_None;
1315 Py_INCREF(exception2);
1316 }
1317 if (v2 == NULL) {
1318 v2 = Py_None;
1319 Py_INCREF(v2);
1320 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001321 fflush(stdout);
1322 PySys_WriteStderr("Error in sys.excepthook:\n");
1323 PyErr_Display(exception2, v2, tb2);
1324 PySys_WriteStderr("\nOriginal exception was:\n");
1325 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001326 Py_DECREF(exception2);
1327 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001328 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001329 }
1330 Py_XDECREF(result);
1331 Py_XDECREF(args);
1332 } else {
1333 PySys_WriteStderr("sys.excepthook is missing\n");
1334 PyErr_Display(exception, v, tb);
1335 }
1336 Py_XDECREF(exception);
1337 Py_XDECREF(v);
1338 Py_XDECREF(tb);
1339}
1340
Benjamin Petersone6528212008-07-15 15:32:09 +00001341static void
1342print_exception(PyObject *f, PyObject *value)
1343{
1344 int err = 0;
1345 PyObject *type, *tb;
1346
Benjamin Peterson26582602008-08-23 20:08:07 +00001347 if (!PyExceptionInstance_Check(value)) {
1348 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1349 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1350 PyFile_WriteString(" found\n", f);
1351 return;
1352 }
1353
Benjamin Petersone6528212008-07-15 15:32:09 +00001354 Py_INCREF(value);
1355 fflush(stdout);
1356 type = (PyObject *) Py_TYPE(value);
1357 tb = PyException_GetTraceback(value);
1358 if (tb && tb != Py_None)
1359 err = PyTraceBack_Print(tb, f);
1360 if (err == 0 &&
1361 PyObject_HasAttrString(value, "print_file_and_line"))
1362 {
1363 PyObject *message;
1364 const char *filename, *text;
1365 int lineno, offset;
1366 if (!parse_syntax_error(value, &message, &filename,
1367 &lineno, &offset, &text))
1368 PyErr_Clear();
1369 else {
1370 char buf[10];
1371 PyFile_WriteString(" File \"", f);
1372 if (filename == NULL)
1373 PyFile_WriteString("<string>", f);
1374 else
1375 PyFile_WriteString(filename, f);
1376 PyFile_WriteString("\", line ", f);
1377 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1378 PyFile_WriteString(buf, f);
1379 PyFile_WriteString("\n", f);
1380 if (text != NULL)
1381 print_error_text(f, offset, text);
1382 Py_DECREF(value);
1383 value = message;
1384 /* Can't be bothered to check all those
1385 PyFile_WriteString() calls */
1386 if (PyErr_Occurred())
1387 err = -1;
1388 }
1389 }
1390 if (err) {
1391 /* Don't do anything else */
1392 }
1393 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001394 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001395 char* className;
1396 assert(PyExceptionClass_Check(type));
1397 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001398 if (className != NULL) {
1399 char *dot = strrchr(className, '.');
1400 if (dot != NULL)
1401 className = dot+1;
1402 }
1403
1404 moduleName = PyObject_GetAttrString(type, "__module__");
1405 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1406 {
1407 Py_DECREF(moduleName);
1408 err = PyFile_WriteString("<unknown>", f);
1409 }
1410 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001411 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001412 if (modstr && strcmp(modstr, "builtins"))
1413 {
1414 err = PyFile_WriteString(modstr, f);
1415 err += PyFile_WriteString(".", f);
1416 }
1417 Py_DECREF(moduleName);
1418 }
1419 if (err == 0) {
1420 if (className == NULL)
1421 err = PyFile_WriteString("<unknown>", f);
1422 else
1423 err = PyFile_WriteString(className, f);
1424 }
1425 }
1426 if (err == 0 && (value != Py_None)) {
1427 PyObject *s = PyObject_Str(value);
1428 /* only print colon if the str() of the
1429 object is not the empty string
1430 */
1431 if (s == NULL)
1432 err = -1;
1433 else if (!PyUnicode_Check(s) ||
1434 PyUnicode_GetSize(s) != 0)
1435 err = PyFile_WriteString(": ", f);
1436 if (err == 0)
1437 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1438 Py_XDECREF(s);
1439 }
1440 /* try to write a newline in any case */
1441 err += PyFile_WriteString("\n", f);
1442 Py_XDECREF(tb);
1443 Py_DECREF(value);
1444 /* If an error happened here, don't show it.
1445 XXX This is wrong, but too many callers rely on this behavior. */
1446 if (err != 0)
1447 PyErr_Clear();
1448}
1449
1450static const char *cause_message =
1451 "\nThe above exception was the direct cause "
1452 "of the following exception:\n\n";
1453
1454static const char *context_message =
1455 "\nDuring handling of the above exception, "
1456 "another exception occurred:\n\n";
1457
1458static void
1459print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1460{
1461 int err = 0, res;
1462 PyObject *cause, *context;
1463
1464 if (seen != NULL) {
1465 /* Exception chaining */
1466 if (PySet_Add(seen, value) == -1)
1467 PyErr_Clear();
1468 else if (PyExceptionInstance_Check(value)) {
1469 cause = PyException_GetCause(value);
1470 context = PyException_GetContext(value);
1471 if (cause) {
1472 res = PySet_Contains(seen, cause);
1473 if (res == -1)
1474 PyErr_Clear();
1475 if (res == 0) {
1476 print_exception_recursive(
1477 f, cause, seen);
1478 err |= PyFile_WriteString(
1479 cause_message, f);
1480 }
1481 }
1482 if (context) {
1483 res = PySet_Contains(seen, context);
1484 if (res == -1)
1485 PyErr_Clear();
1486 if (res == 0) {
1487 print_exception_recursive(
1488 f, context, seen);
1489 err |= PyFile_WriteString(
1490 context_message, f);
1491 }
1492 }
1493 Py_XDECREF(context);
1494 Py_XDECREF(cause);
1495 }
1496 }
1497 print_exception(f, value);
1498 if (err != 0)
1499 PyErr_Clear();
1500}
1501
Thomas Wouters477c8d52006-05-27 19:21:47 +00001502void
1503PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001504{
Benjamin Petersone6528212008-07-15 15:32:09 +00001505 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001506 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001507 if (f == Py_None) {
1508 /* pass */
1509 }
1510 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001511 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001512 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001513 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001514 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001515 /* We choose to ignore seen being possibly NULL, and report
1516 at least the main exception (it could be a MemoryError).
1517 */
1518 seen = PySet_New(NULL);
1519 if (seen == NULL)
1520 PyErr_Clear();
1521 print_exception_recursive(f, value, seen);
1522 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001523 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001524}
1525
Guido van Rossum82598051997-03-05 00:20:32 +00001526PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001527PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001528 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001529{
Neal Norwitze92fba02006-03-04 18:52:26 +00001530 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001531 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001532 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001533 if (arena == NULL)
1534 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001535
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001536 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001537 if (mod != NULL)
1538 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001539 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001540 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001541}
1542
1543PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001544PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001545 PyObject *locals, int closeit, PyCompilerFlags *flags)
1546{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001547 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001548 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001549 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001550 if (arena == NULL)
1551 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001552
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001553 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001554 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001555 if (closeit)
1556 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001557 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001558 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001559 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001560 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001561 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001562 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001563 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001564}
1565
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001566static void
1567flush_io(void)
1568{
1569 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001570 PyObject *type, *value, *traceback;
1571
1572 /* Save the current exception */
1573 PyErr_Fetch(&type, &value, &traceback);
1574
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001575 f = PySys_GetObject("stderr");
1576 if (f != NULL) {
1577 r = PyObject_CallMethod(f, "flush", "");
1578 if (r)
1579 Py_DECREF(r);
1580 else
1581 PyErr_Clear();
1582 }
1583 f = PySys_GetObject("stdout");
1584 if (f != NULL) {
1585 r = PyObject_CallMethod(f, "flush", "");
1586 if (r)
1587 Py_DECREF(r);
1588 else
1589 PyErr_Clear();
1590 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001591
1592 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001593}
1594
Guido van Rossum82598051997-03-05 00:20:32 +00001595static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001596run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001597 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001598{
Guido van Rossum82598051997-03-05 00:20:32 +00001599 PyCodeObject *co;
1600 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001601 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001602 if (co == NULL)
1603 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001604 v = PyEval_EvalCode(co, globals, locals);
1605 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001606 return v;
1607}
1608
Guido van Rossum82598051997-03-05 00:20:32 +00001609static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001610run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001611 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001612{
Guido van Rossum82598051997-03-05 00:20:32 +00001613 PyCodeObject *co;
1614 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001615 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001616 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001617
Guido van Rossum82598051997-03-05 00:20:32 +00001618 magic = PyMarshal_ReadLongFromFile(fp);
1619 if (magic != PyImport_GetMagicNumber()) {
1620 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001621 "Bad magic number in .pyc file");
1622 return NULL;
1623 }
Guido van Rossum82598051997-03-05 00:20:32 +00001624 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001625 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001626 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001627 if (v == NULL || !PyCode_Check(v)) {
1628 Py_XDECREF(v);
1629 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001630 "Bad code object in .pyc file");
1631 return NULL;
1632 }
Guido van Rossum82598051997-03-05 00:20:32 +00001633 co = (PyCodeObject *)v;
1634 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001635 if (v && flags)
1636 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001637 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001638 return v;
1639}
1640
Guido van Rossum82598051997-03-05 00:20:32 +00001641PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001642Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001643 PyCompilerFlags *flags)
1644{
Guido van Rossum82598051997-03-05 00:20:32 +00001645 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001646 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001647 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001648 if (arena == NULL)
1649 return NULL;
1650
1651 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001652 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001653 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001654 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001655 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001656 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001657 PyObject *result = PyAST_mod2obj(mod);
1658 PyArena_Free(arena);
1659 return result;
1660 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001661 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001662 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001663 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001664}
1665
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001666struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001667Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001668{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001669 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001670 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001671 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001672 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001673 if (arena == NULL)
1674 return NULL;
1675
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001676 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001677 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001678 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001679 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001680 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001681 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001683 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001684 return st;
1685}
1686
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687/* Preferred access to parser is through AST. */
1688mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001689PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001690 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001691{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001692 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001693 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001695 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001696
1697 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001698 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001699 &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001700 if (flags == NULL) {
1701 localflags.cf_flags = 0;
1702 flags = &localflags;
1703 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001705 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001706 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001707 PyNode_Free(n);
1708 return mod;
1709 }
1710 else {
1711 err_input(&err);
1712 return NULL;
1713 }
1714}
1715
1716mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001717PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1718 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001719 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001720 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001721{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001722 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001723 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001724 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001725 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001726
Christian Heimes4d6ec852008-03-26 22:34:47 +00001727 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001728 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001729 start, ps1, ps2, &err, &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001730 if (flags == NULL) {
1731 localflags.cf_flags = 0;
1732 flags = &localflags;
1733 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001734 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001735 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001736 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001737 PyNode_Free(n);
1738 return mod;
1739 }
1740 else {
1741 err_input(&err);
1742 if (errcode)
1743 *errcode = err.error;
1744 return NULL;
1745 }
1746}
1747
Guido van Rossuma110aa61994-08-29 12:50:44 +00001748/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001749
Guido van Rossuma110aa61994-08-29 12:50:44 +00001750node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001751PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001752{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001753 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001754 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1755 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001756 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001757 if (n == NULL)
1758 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001759
Guido van Rossuma110aa61994-08-29 12:50:44 +00001760 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001761}
1762
Guido van Rossuma110aa61994-08-29 12:50:44 +00001763/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001764
Guido van Rossuma110aa61994-08-29 12:50:44 +00001765node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001766PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001767{
Tim Petersfe2127d2001-07-16 05:37:24 +00001768 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001769 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1770 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001771 if (n == NULL)
1772 err_input(&err);
1773 return n;
1774}
1775
1776node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001777PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001778 int start, int flags)
1779{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001780 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001781 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1782 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001783 if (n == NULL)
1784 err_input(&err);
1785 return n;
1786}
1787
1788node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001789PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001790{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001791 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001792}
1793
Guido van Rossum66ebd912003-04-17 16:02:26 +00001794/* May want to move a more generalized form of this to parsetok.c or
1795 even parser modules. */
1796
1797void
1798PyParser_SetError(perrdetail *err)
1799{
1800 err_input(err);
1801}
1802
Guido van Rossuma110aa61994-08-29 12:50:44 +00001803/* Set the error appropriate to the given input error code (see errcode.h) */
1804
1805static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001806err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001807{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001808 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001809 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001810 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001811 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001812 switch (err->error) {
1813 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001814 errtype = PyExc_IndentationError;
1815 if (err->expected == INDENT)
1816 msg = "expected an indented block";
1817 else if (err->token == INDENT)
1818 msg = "unexpected indent";
1819 else if (err->token == DEDENT)
1820 msg = "unexpected unindent";
1821 else {
1822 errtype = PyExc_SyntaxError;
1823 msg = "invalid syntax";
1824 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001825 break;
1826 case E_TOKEN:
1827 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001828 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001829 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001830 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001831 break;
1832 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001833 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001834 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001835 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001836 if (!PyErr_Occurred())
1837 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001838 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001839 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001840 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001841 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001842 case E_EOF:
1843 msg = "unexpected EOF while parsing";
1844 break;
Fred Drake85f36392000-07-11 17:53:00 +00001845 case E_TABSPACE:
1846 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001847 msg = "inconsistent use of tabs and spaces in indentation";
1848 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001849 case E_OVERFLOW:
1850 msg = "expression too long";
1851 break;
Fred Drake85f36392000-07-11 17:53:00 +00001852 case E_DEDENT:
1853 errtype = PyExc_IndentationError;
1854 msg = "unindent does not match any outer indentation level";
1855 break;
1856 case E_TOODEEP:
1857 errtype = PyExc_IndentationError;
1858 msg = "too many levels of indentation";
1859 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001860 case E_DECODE: {
1861 PyObject *type, *value, *tb;
1862 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001863 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001864 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001865 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001866 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001867 }
1868 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001869 if (msg == NULL)
1870 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001871 Py_XDECREF(type);
1872 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001873 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001874 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001875 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001876 case E_LINECONT:
1877 msg = "unexpected character after line continuation character";
1878 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001879
1880 case E_IDENTIFIER:
1881 msg = "invalid character in identifier";
1882 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001883 default:
1884 fprintf(stderr, "error=%d\n", err->error);
1885 msg = "unknown parsing error";
1886 break;
1887 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001888 /* err->text may not be UTF-8 in case of decoding errors.
1889 Explicitly convert to an object. */
1890 if (!err->text) {
1891 errtext = Py_None;
1892 Py_INCREF(Py_None);
1893 } else {
1894 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1895 "replace");
1896 }
1897 v = Py_BuildValue("(ziiN)", err->filename,
1898 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001899 w = NULL;
1900 if (v != NULL)
1901 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001902 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001903 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001904 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001905 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001906cleanup:
1907 if (err->text != NULL) {
1908 PyObject_FREE(err->text);
1909 err->text = NULL;
1910 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001911}
1912
1913/* Print fatal error message and abort */
1914
1915void
Tim Peters7c321a82002-07-09 02:57:01 +00001916Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001917{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001918 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001919 if (PyErr_Occurred()) {
1920 PyErr_Print();
1921 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001922#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +00001923 {
1924 size_t len = strlen(msg);
1925 WCHAR* buffer;
1926 size_t i;
1927
1928 /* Convert the message to wchar_t. This uses a simple one-to-one
1929 conversion, assuming that the this error message actually uses ASCII
1930 only. If this ceases to be true, we will have to convert. */
1931 buffer = alloca( (len+1) * (sizeof *buffer));
1932 for( i=0; i<=len; ++i)
1933 buffer[i] = msg[i];
1934 OutputDebugStringW(L"Fatal Python error: ");
1935 OutputDebugStringW(buffer);
1936 OutputDebugStringW(L"\n");
1937 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001938#ifdef _DEBUG
1939 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001940#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001941#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001942 abort();
1943}
1944
1945/* Clean up and exit */
1946
Guido van Rossuma110aa61994-08-29 12:50:44 +00001947#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001948#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001949#endif
1950
Collin Winter670e6922007-03-21 02:57:17 +00001951static void (*pyexitfunc)(void) = NULL;
1952/* For the atexit module. */
1953void _Py_PyAtExit(void (*func)(void))
1954{
1955 pyexitfunc = func;
1956}
1957
1958static void
1959call_py_exitfuncs(void)
1960{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001961 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00001962 return;
1963
1964 (*pyexitfunc)();
1965 PyErr_Clear();
1966}
1967
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001968#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001969static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001970static int nexitfuncs = 0;
1971
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001972int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001973{
1974 if (nexitfuncs >= NEXITFUNCS)
1975 return -1;
1976 exitfuncs[nexitfuncs++] = func;
1977 return 0;
1978}
1979
Guido van Rossumcc283f51997-08-05 02:22:03 +00001980static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001981call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001982{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001983 while (nexitfuncs > 0)
1984 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001985
1986 fflush(stdout);
1987 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001988}
1989
1990void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001991Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001992{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001993 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001994
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001995 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001996}
1997
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001998static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001999initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002000{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002001#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002002 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002003#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002004#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002005 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002006#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002007#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002008 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002009#endif
Guido van Rossum82598051997-03-05 00:20:32 +00002010 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002011}
2012
Guido van Rossum7433b121997-02-14 19:45:36 +00002013
2014/*
2015 * The file descriptor fd is considered ``interactive'' if either
2016 * a) isatty(fd) is TRUE, or
2017 * b) the -i flag was given, and the filename associated with
2018 * the descriptor is NULL or "<stdin>" or "???".
2019 */
2020int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002021Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002022{
2023 if (isatty((int)fileno(fp)))
2024 return 1;
2025 if (!Py_InteractiveFlag)
2026 return 0;
2027 return (filename == NULL) ||
2028 (strcmp(filename, "<stdin>") == 0) ||
2029 (strcmp(filename, "???") == 0);
2030}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002031
2032
Tim Petersd08e3822003-04-17 15:24:21 +00002033#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002034#if defined(WIN32) && defined(_MSC_VER)
2035
2036/* Stack checking for Microsoft C */
2037
2038#include <malloc.h>
2039#include <excpt.h>
2040
Fred Drakee8de31c2000-08-31 05:38:39 +00002041/*
2042 * Return non-zero when we run out of memory on the stack; zero otherwise.
2043 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002044int
Fred Drake399739f2000-08-31 05:52:44 +00002045PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002046{
2047 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00002048 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002049 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00002050 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002051 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00002052 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00002053 EXCEPTION_EXECUTE_HANDLER :
2054 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00002055 int errcode = _resetstkoflw();
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +00002056 if (errcode == 0)
Christian Heimes7131fd92008-02-19 14:21:46 +00002057 {
2058 Py_FatalError("Could not reset the stack!");
2059 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002060 }
2061 return 1;
2062}
2063
2064#endif /* WIN32 && _MSC_VER */
2065
2066/* Alternate implementations can be added here... */
2067
2068#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002069
2070
2071/* Wrappers around sigaction() or signal(). */
2072
2073PyOS_sighandler_t
2074PyOS_getsig(int sig)
2075{
2076#ifdef HAVE_SIGACTION
2077 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002078 if (sigaction(sig, NULL, &context) == -1)
2079 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002080 return context.sa_handler;
2081#else
2082 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002083/* Special signal handling for the secure CRT in Visual Studio 2005 */
2084#if defined(_MSC_VER) && _MSC_VER >= 1400
2085 switch (sig) {
2086 /* Only these signals are valid */
2087 case SIGINT:
2088 case SIGILL:
2089 case SIGFPE:
2090 case SIGSEGV:
2091 case SIGTERM:
2092 case SIGBREAK:
2093 case SIGABRT:
2094 break;
2095 /* Don't call signal() with other values or it will assert */
2096 default:
2097 return SIG_ERR;
2098 }
2099#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002100 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002101 if (handler != SIG_ERR)
2102 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002103 return handler;
2104#endif
2105}
2106
2107PyOS_sighandler_t
2108PyOS_setsig(int sig, PyOS_sighandler_t handler)
2109{
2110#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002111 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002112 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002113 sigemptyset(&context.sa_mask);
2114 context.sa_flags = 0;
2115 if (sigaction(sig, &context, &ocontext) == -1)
2116 return SIG_ERR;
2117 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002118#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002119 PyOS_sighandler_t oldhandler;
2120 oldhandler = signal(sig, handler);
2121#ifdef HAVE_SIGINTERRUPT
2122 siginterrupt(sig, 1);
2123#endif
2124 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002125#endif
2126}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002127
2128/* Deprecated C API functions still provided for binary compatiblity */
2129
2130#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002131PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002132PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2133{
2134 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2135}
2136
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002137#undef PyParser_SimpleParseString
2138PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002139PyParser_SimpleParseString(const char *str, int start)
2140{
2141 return PyParser_SimpleParseStringFlags(str, start, 0);
2142}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002143
2144#undef PyRun_AnyFile
2145PyAPI_FUNC(int)
2146PyRun_AnyFile(FILE *fp, const char *name)
2147{
2148 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2149}
2150
2151#undef PyRun_AnyFileEx
2152PyAPI_FUNC(int)
2153PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2154{
2155 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2156}
2157
2158#undef PyRun_AnyFileFlags
2159PyAPI_FUNC(int)
2160PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2161{
2162 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2163}
2164
2165#undef PyRun_File
2166PyAPI_FUNC(PyObject *)
2167PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2168{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002169 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002170}
2171
2172#undef PyRun_FileEx
2173PyAPI_FUNC(PyObject *)
2174PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2175{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002176 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002177}
2178
2179#undef PyRun_FileFlags
2180PyAPI_FUNC(PyObject *)
2181PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2182 PyCompilerFlags *flags)
2183{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002184 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002185}
2186
2187#undef PyRun_SimpleFile
2188PyAPI_FUNC(int)
2189PyRun_SimpleFile(FILE *f, const char *p)
2190{
2191 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2192}
2193
2194#undef PyRun_SimpleFileEx
2195PyAPI_FUNC(int)
2196PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2197{
2198 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2199}
2200
2201
2202#undef PyRun_String
2203PyAPI_FUNC(PyObject *)
2204PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2205{
2206 return PyRun_StringFlags(str, s, g, l, NULL);
2207}
2208
2209#undef PyRun_SimpleString
2210PyAPI_FUNC(int)
2211PyRun_SimpleString(const char *s)
2212{
2213 return PyRun_SimpleStringFlags(s, NULL);
2214}
2215
2216#undef Py_CompileString
2217PyAPI_FUNC(PyObject *)
2218Py_CompileString(const char *str, const char *p, int s)
2219{
2220 return Py_CompileStringFlags(str, p, s, NULL);
2221}
2222
2223#undef PyRun_InteractiveOne
2224PyAPI_FUNC(int)
2225PyRun_InteractiveOne(FILE *f, const char *p)
2226{
2227 return PyRun_InteractiveOneFlags(f, p, NULL);
2228}
2229
2230#undef PyRun_InteractiveLoop
2231PyAPI_FUNC(int)
2232PyRun_InteractiveLoop(FILE *f, const char *p)
2233{
2234 return PyRun_InteractiveLoopFlags(f, p, NULL);
2235}
2236
2237#ifdef __cplusplus
2238}
2239#endif