blob: 1ee062fe6fa7b5675f778eed66a8104e9917ee57 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000021
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000025
Martin v. Löwis73d538b2003-03-05 15:13:47 +000026#ifdef HAVE_LANGINFO_H
27#include <locale.h>
28#include <langinfo.h>
29#endif
30
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000031#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000032#undef BYTE
33#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000034#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000035#endif
36
Neal Norwitz4281cef2006-03-04 19:58:13 +000037#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000038#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000039#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000040#define PRINT_TOTAL_REFS() fprintf(stderr, \
41 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
42 _Py_GetRefTotal())
43#endif
44
45#ifdef __cplusplus
46extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000047#endif
48
Martin v. Löwis790465f2008-04-05 20:41:37 +000049extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000050
Guido van Rossum82598051997-03-05 00:20:32 +000051extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000052
Guido van Rossumb73cc041993-11-01 16:28:59 +000053/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000054static void initmain(void);
55static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000056static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000057static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000058static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000059 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000060static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000061 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000062static void err_input(perrdetail *);
63static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000064static void call_py_exitfuncs(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000065static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000066extern void _PyUnicode_Init(void);
67extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000068extern int _PyLong_Init(void);
69extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000070
Mark Hammond8d98d2c2003-04-19 15:41:53 +000071#ifdef WITH_THREAD
72extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
73extern void _PyGILState_Fini(void);
74#endif /* WITH_THREAD */
75
Guido van Rossum82598051997-03-05 00:20:32 +000076int Py_DebugFlag; /* Needed by parser.c */
77int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000078int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000079int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000080int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000081int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000082int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000083int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000084int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000085int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000086int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000087
Christian Heimes33fe8092008-04-13 13:53:33 +000088/* PyModule_GetWarningsModule is no longer necessary as of 2.6
89since _warnings is builtin. This API should not be used. */
90PyObject *
91PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000092{
Christian Heimes33fe8092008-04-13 13:53:33 +000093 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000094}
Mark Hammonda43fd0c2003-02-19 00:33:33 +000095
Guido van Rossum25ce5661997-08-02 03:10:38 +000096static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000097
Thomas Wouters7e474022000-07-16 12:04:32 +000098/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +000099
100int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000101Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000102{
103 return initialized;
104}
105
Guido van Rossum25ce5661997-08-02 03:10:38 +0000106/* Global initializations. Can be undone by Py_Finalize(). Don't
107 call this twice without an intervening Py_Finalize() call. When
108 initializations fail, a fatal error is issued and the function does
109 not return. On return, the first thread and interpreter state have
110 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000111
Guido van Rossum25ce5661997-08-02 03:10:38 +0000112 Locking: you must hold the interpreter lock while calling this.
113 (If the lock has not yet been initialized, that's equivalent to
114 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000117
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000118static int
119add_flag(int flag, const char *envs)
120{
121 int env = atoi(envs);
122 if (flag < env)
123 flag = env;
124 if (flag < 1)
125 flag = 1;
126 return flag;
127}
128
Guido van Rossuma027efa1997-05-05 20:56:21 +0000129void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000130Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000131{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000132 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000133 PyThreadState *tstate;
Guido van Rossum826d8972007-10-30 18:34:07 +0000134 PyObject *bimod, *sysmod, *pstderr;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000135 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000136#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000137 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000138#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000139 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000140
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000141 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000142 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000143 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000144
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000145#ifdef HAVE_SETLOCALE
146 /* Set up the LC_CTYPE locale, so we can obtain
147 the locale's charset without having to switch
148 locales. */
149 setlocale(LC_CTYPE, "");
150#endif
151
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000152 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000153 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000154 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000155 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000156 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000157 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Christian Heimes790c8232008-01-07 21:14:23 +0000158 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
159 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000160
Guido van Rossuma027efa1997-05-05 20:56:21 +0000161 interp = PyInterpreterState_New();
162 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000163 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000164
Guido van Rossuma027efa1997-05-05 20:56:21 +0000165 tstate = PyThreadState_New(interp);
166 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000167 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000168 (void) PyThreadState_Swap(tstate);
169
Guido van Rossum70d893a2001-08-16 08:21:42 +0000170 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000171
Neal Norwitzb2501f42002-12-31 03:42:13 +0000172 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000173 Py_FatalError("Py_Initialize: can't init frames");
174
Guido van Rossumddefaf32007-01-14 03:31:43 +0000175 if (!_PyLong_Init())
176 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000177
Christian Heimes9c4756e2008-05-26 13:22:05 +0000178 if (!PyByteArray_Init())
Neal Norwitz6968b052007-02-27 19:02:19 +0000179 Py_FatalError("Py_Initialize: can't init bytes");
180
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000181 _PyFloat_Init();
182
Guido van Rossum25ce5661997-08-02 03:10:38 +0000183 interp->modules = PyDict_New();
184 if (interp->modules == NULL)
185 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000186 interp->modules_reloading = PyDict_New();
187 if (interp->modules_reloading == NULL)
188 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000189
Guido van Rossumc94044c2000-03-10 23:03:54 +0000190 /* Init Unicode implementation; relies on the codec registry */
191 _PyUnicode_Init();
192
Barry Warsawf242aa02000-05-25 23:09:49 +0000193 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000194 if (bimod == NULL)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000195 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Martin v. Löwis1a214512008-06-11 05:26:20 +0000196 _PyImport_FixupExtension(bimod, "builtins", "builtins");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000197 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000198 if (interp->builtins == NULL)
199 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000200 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000201
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000202 /* initialize builtin exceptions */
203 _PyExc_Init();
204
Guido van Rossum25ce5661997-08-02 03:10:38 +0000205 sysmod = _PySys_Init();
206 if (sysmod == NULL)
207 Py_FatalError("Py_Initialize: can't initialize sys");
208 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000209 if (interp->sysdict == NULL)
210 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000211 Py_INCREF(interp->sysdict);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000212 _PyImport_FixupExtension(sysmod, "sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000213 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000214 PyDict_SetItemString(interp->sysdict, "modules",
215 interp->modules);
216
Guido van Rossum826d8972007-10-30 18:34:07 +0000217 /* Set up a preliminary stderr printer until we have enough
218 infrastructure for the io module in place. */
219 pstderr = PyFile_NewStdPrinter(fileno(stderr));
220 if (pstderr == NULL)
221 Py_FatalError("Py_Initialize: can't set preliminary stderr");
222 PySys_SetObject("stderr", pstderr);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000223 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000224
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000225 _PyImport_Init();
226
Just van Rossum52e14d62002-12-30 22:08:05 +0000227 _PyImportHooks_Init();
228
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000229 if (install_sigs)
230 initsigs(); /* Signal handling stuff, including initintr() */
Christian Heimes33fe8092008-04-13 13:53:33 +0000231
Georg Brandl86b2fb92008-07-16 03:43:04 +0000232 /* Initialize warnings. */
233 _PyWarnings_Init();
234 if (PySys_HasWarnOptions()) {
235 PyObject *warnings_module = PyImport_ImportModule("warnings");
236 if (!warnings_module)
237 PyErr_Clear();
238 Py_XDECREF(warnings_module);
239 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240
241 initmain(); /* Module __main__ */
Alexandre Vassalotti77250f42008-05-06 19:48:38 +0000242 if (!Py_NoSiteFlag)
243 initsite(); /* Module site */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000244 if (initstdio() < 0)
245 Py_FatalError(
246 "Py_Initialize: can't initialize sys standard streams");
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000247
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000248 /* auto-thread-state API, if available */
249#ifdef WITH_THREAD
250 _PyGILState_Init(interp, tstate);
251#endif /* WITH_THREAD */
252
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000253#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000254 /* On Unix, set the file system encoding according to the
255 user's preference, if the CODESET names a well-known
256 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000257 initialized by other means. Also set the encoding of
258 stdin and stdout if these are terminals. */
259
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000260 codeset = nl_langinfo(CODESET);
261 if (codeset && *codeset) {
Marc-André Lemburgb2750b52008-06-06 12:18:17 +0000262 if (PyCodec_KnownEncoding(codeset))
263 codeset = strdup(codeset);
264 else
265 codeset = NULL;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000266 } else
267 codeset = NULL;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000268
269 if (codeset) {
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000270 if (!Py_FileSystemDefaultEncoding)
271 Py_FileSystemDefaultEncoding = codeset;
272 else
273 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000274 }
275#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000276}
277
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000278void
279Py_Initialize(void)
280{
281 Py_InitializeEx(1);
282}
283
284
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000285#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000287#endif
288
Guido van Rossume8432ac2007-07-09 15:04:50 +0000289/* Flush stdout and stderr */
290
Neal Norwitz2bad9702007-08-27 06:19:22 +0000291static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000292flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000293{
294 PyObject *fout = PySys_GetObject("stdout");
295 PyObject *ferr = PySys_GetObject("stderr");
296 PyObject *tmp;
297
Christian Heimes2be03732007-11-15 02:26:46 +0000298 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000299 tmp = PyObject_CallMethod(fout, "flush", "");
300 if (tmp == NULL)
301 PyErr_Clear();
302 else
303 Py_DECREF(tmp);
304 }
305
Christian Heimes2be03732007-11-15 02:26:46 +0000306 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000307 tmp = PyObject_CallMethod(ferr, "flush", "");
308 if (tmp == NULL)
309 PyErr_Clear();
310 else
311 Py_DECREF(tmp);
312 }
313}
314
Guido van Rossum25ce5661997-08-02 03:10:38 +0000315/* Undo the effect of Py_Initialize().
316
317 Beware: if multiple interpreter and/or thread states exist, these
318 are not wiped out; only the current thread and interpreter state
319 are deleted. But since everything else is deleted, those other
320 interpreter and thread states should no longer be used.
321
322 (XXX We should do better, e.g. wipe out all interpreters and
323 threads.)
324
325 Locking: as above.
326
327*/
328
329void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000330Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000331{
332 PyInterpreterState *interp;
333 PyThreadState *tstate;
334
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000335 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000336 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000337
Tim Peters384fd102001-01-21 03:40:37 +0000338 /* The interpreter is still entirely intact at this point, and the
339 * exit funcs may be relying on that. In particular, if some thread
340 * or exit func is still waiting to do an import, the import machinery
341 * expects Py_IsInitialized() to return true. So don't say the
342 * interpreter is uninitialized until after the exit funcs have run.
343 * Note that Threading.py uses an exit func to do a join on all the
344 * threads created thru it, so this also protects pending imports in
345 * the threads created via Threading.
346 */
Collin Winter670e6922007-03-21 02:57:17 +0000347 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000348 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000349
Guido van Rossume8432ac2007-07-09 15:04:50 +0000350 /* Flush stdout+stderr */
351 flush_std_files();
352
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000353 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000354 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000355 interp = tstate->interp;
356
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000357 /* Disable signal handling */
358 PyOS_FiniInterrupts();
359
Christian Heimes26855632008-01-27 23:50:43 +0000360 /* Clear type lookup cache */
361 PyType_ClearCache();
362
Guido van Rossume13ddc92003-04-17 17:29:22 +0000363 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000364 * before all modules are destroyed.
365 * XXX If a __del__ or weakref callback is triggered here, and tries to
366 * XXX import a module, bad things can happen, because Python no
367 * XXX longer believes it's initialized.
368 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
369 * XXX is easy to provoke that way. I've also seen, e.g.,
370 * XXX Exception exceptions.ImportError: 'No module named sha'
371 * XXX in <function callback at 0x008F5718> ignored
372 * XXX but I'm unclear on exactly how that one happens. In any case,
373 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000374 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000375 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000376#ifdef COUNT_ALLOCS
377 /* With COUNT_ALLOCS, it helps to run GC multiple times:
378 each collection might release some types from the type
379 list, so they become garbage. */
380 while (PyGC_Collect() > 0)
381 /* nothing */;
382#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000383
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000384 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000385 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000386
Guido van Rossume8432ac2007-07-09 15:04:50 +0000387 /* Flush stdout+stderr (again, in case more was printed) */
388 flush_std_files();
389
Guido van Rossume13ddc92003-04-17 17:29:22 +0000390 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000391 * new-style class definitions, for example.
392 * XXX This is disabled because it caused too many problems. If
393 * XXX a __del__ or weakref callback triggers here, Python code has
394 * XXX a hard time running, because even the sys module has been
395 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
396 * XXX One symptom is a sequence of information-free messages
397 * XXX coming from threads (if a __del__ or callback is invoked,
398 * XXX other threads can execute too, and any exception they encounter
399 * XXX triggers a comedy of errors as subsystem after subsystem
400 * XXX fails to find what it *expects* to find in sys to help report
401 * XXX the exception and consequent unexpected failures). I've also
402 * XXX seen segfaults then, after adding print statements to the
403 * XXX Python code getting called.
404 */
405#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000406 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000407#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000408
Guido van Rossum1707aad1997-12-08 23:43:45 +0000409 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
410 _PyImport_Fini();
411
412 /* Debugging stuff */
413#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000414 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000415#endif
416
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000418
Tim Peters9cf25ce2003-04-17 15:21:01 +0000419#ifdef Py_TRACE_REFS
420 /* Display all objects still alive -- this can invoke arbitrary
421 * __repr__ overrides, so requires a mostly-intact interpreter.
422 * Alas, a lot of stuff may still be alive now that will be cleaned
423 * up later.
424 */
Tim Peters269b2a62003-04-17 19:52:29 +0000425 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000426 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000427#endif /* Py_TRACE_REFS */
428
Guido van Rossumd922fa42003-04-15 14:10:09 +0000429 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000430 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000431
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000432 /* Now we decref the exception classes. After this point nothing
433 can raise an exception. That's okay, because each Fini() method
434 below has been checked to make sure no exceptions are ever
435 raised.
436 */
437
438 _PyExc_Fini();
439
Christian Heimes7d2ff882007-11-30 14:35:04 +0000440 /* Cleanup auto-thread-state */
441#ifdef WITH_THREAD
442 _PyGILState_Fini();
443#endif /* WITH_THREAD */
444
Guido van Rossumd922fa42003-04-15 14:10:09 +0000445 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000446 PyThreadState_Swap(NULL);
447 PyInterpreterState_Delete(interp);
448
Guido van Rossumd922fa42003-04-15 14:10:09 +0000449 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000450 PyMethod_Fini();
451 PyFrame_Fini();
452 PyCFunction_Fini();
453 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000454 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000455 PySet_Fini();
Christian Heimes72b710a2008-05-26 13:28:38 +0000456 PyBytes_Fini();
Christian Heimes9c4756e2008-05-26 13:22:05 +0000457 PyByteArray_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000458 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000459 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000460 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000461
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000462 /* Cleanup Unicode implementation */
463 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000464
Christian Heimesc8967002007-11-30 10:18:26 +0000465 /* reset file system default encoding */
466 if (!Py_HasFileSystemDefaultEncoding) {
467 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000468 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000469 }
470
Guido van Rossumcc283f51997-08-05 02:22:03 +0000471 /* XXX Still allocated:
472 - various static ad-hoc pointers to interned strings
473 - int and float free list blocks
474 - whatever various modules and libraries allocate
475 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000476
477 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000478
Tim Peters269b2a62003-04-17 19:52:29 +0000479#ifdef Py_TRACE_REFS
480 /* Display addresses (& refcnts) of all objects still alive.
481 * An address can be used to find the repr of the object, printed
482 * above by _Py_PrintReferences.
483 */
484 if (Py_GETENV("PYTHONDUMPREFS"))
485 _Py_PrintReferenceAddresses(stderr);
486#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000487#ifdef PYMALLOC_DEBUG
488 if (Py_GETENV("PYTHONMALLOCSTATS"))
489 _PyObject_DebugMallocStats();
490#endif
491
Guido van Rossumcc283f51997-08-05 02:22:03 +0000492 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000493}
494
495/* Create and initialize a new interpreter and thread, and return the
496 new thread. This requires that Py_Initialize() has been called
497 first.
498
499 Unsuccessful initialization yields a NULL pointer. Note that *no*
500 exception information is available even in this case -- the
501 exception information is held in the thread, and there is no
502 thread.
503
504 Locking: as above.
505
506*/
507
508PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000509Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000510{
511 PyInterpreterState *interp;
512 PyThreadState *tstate, *save_tstate;
513 PyObject *bimod, *sysmod;
514
515 if (!initialized)
516 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
517
518 interp = PyInterpreterState_New();
519 if (interp == NULL)
520 return NULL;
521
522 tstate = PyThreadState_New(interp);
523 if (tstate == NULL) {
524 PyInterpreterState_Delete(interp);
525 return NULL;
526 }
527
528 save_tstate = PyThreadState_Swap(tstate);
529
530 /* XXX The following is lax in error checking */
531
532 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000533 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000534
Georg Brandl1a3284e2007-12-02 09:40:06 +0000535 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000536 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000537 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000538 if (interp->builtins == NULL)
539 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000540 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000541 }
542 sysmod = _PyImport_FindExtension("sys", "sys");
543 if (bimod != NULL && sysmod != NULL) {
544 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000545 if (interp->sysdict == NULL)
546 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000547 Py_INCREF(interp->sysdict);
548 PySys_SetPath(Py_GetPath());
549 PyDict_SetItemString(interp->sysdict, "modules",
550 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000551 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000552 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000553 if (!Py_NoSiteFlag)
554 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555 }
556
557 if (!PyErr_Occurred())
558 return tstate;
559
Thomas Wouters89f507f2006-12-13 04:49:30 +0000560handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561 /* Oops, it didn't work. Undo it all. */
562
563 PyErr_Print();
564 PyThreadState_Clear(tstate);
565 PyThreadState_Swap(save_tstate);
566 PyThreadState_Delete(tstate);
567 PyInterpreterState_Delete(interp);
568
569 return NULL;
570}
571
572/* Delete an interpreter and its last thread. This requires that the
573 given thread state is current, that the thread has no remaining
574 frames, and that it is its interpreter's only remaining thread.
575 It is a fatal error to violate these constraints.
576
577 (Py_Finalize() doesn't have these constraints -- it zaps
578 everything, regardless.)
579
580 Locking: as above.
581
582*/
583
584void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000585Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000586{
587 PyInterpreterState *interp = tstate->interp;
588
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000589 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590 Py_FatalError("Py_EndInterpreter: thread is not current");
591 if (tstate->frame != NULL)
592 Py_FatalError("Py_EndInterpreter: thread still has a frame");
593 if (tstate != interp->tstate_head || tstate->next != NULL)
594 Py_FatalError("Py_EndInterpreter: not the last thread");
595
596 PyImport_Cleanup();
597 PyInterpreterState_Clear(interp);
598 PyThreadState_Swap(NULL);
599 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000600}
601
Martin v. Löwis790465f2008-04-05 20:41:37 +0000602static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000603
604void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000605Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000606{
607 if (pn && *pn)
608 progname = pn;
609}
610
Martin v. Löwis790465f2008-04-05 20:41:37 +0000611wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000612Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000613{
614 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000615}
616
Martin v. Löwis790465f2008-04-05 20:41:37 +0000617static wchar_t *default_home = NULL;
618static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000619
620void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000621Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000622{
623 default_home = home;
624}
625
Martin v. Löwis790465f2008-04-05 20:41:37 +0000626wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000627Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000628{
Martin v. Löwis790465f2008-04-05 20:41:37 +0000629 wchar_t *home = default_home;
630 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
631 char* chome = Py_GETENV("PYTHONHOME");
632 if (chome) {
633 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
634 if (r != (size_t)-1 && r <= PATH_MAX)
635 home = env_home;
636 }
637
638 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000639 return home;
640}
641
Guido van Rossum6135a871995-01-09 17:53:26 +0000642/* Create __main__ module */
643
644static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000645initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000646{
Guido van Rossum82598051997-03-05 00:20:32 +0000647 PyObject *m, *d;
648 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000649 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000650 Py_FatalError("can't create __main__ module");
651 d = PyModule_GetDict(m);
652 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000653 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000654 if (bimod == NULL ||
655 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000656 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000657 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000658 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000659}
660
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000661/* Import the site module (not into __main__ though) */
662
663static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000664initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000665{
666 PyObject *m, *f;
667 m = PyImport_ImportModule("site");
668 if (m == NULL) {
669 f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +0000670 if (f == NULL || f == Py_None)
671 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000672 if (Py_VerboseFlag) {
673 PyFile_WriteString(
674 "'import site' failed; traceback:\n", f);
675 PyErr_Print();
676 }
677 else {
678 PyFile_WriteString(
679 "'import site' failed; use -v for traceback\n", f);
680 PyErr_Clear();
681 }
682 }
683 else {
684 Py_DECREF(m);
685 }
686}
687
Georg Brandl1a3284e2007-12-02 09:40:06 +0000688/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000689static int
690initstdio(void)
691{
692 PyObject *iomod = NULL, *wrapper;
693 PyObject *bimod = NULL;
694 PyObject *m;
695 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000696 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000697 PyObject * encoding_attr;
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +0000698 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000699
700 /* Hack to avoid a nasty recursion issue when Python is invoked
701 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
702 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
703 goto error;
704 }
705 Py_DECREF(m);
706
707 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
708 goto error;
709 }
710 Py_DECREF(m);
711
Georg Brandl1a3284e2007-12-02 09:40:06 +0000712 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000713 goto error;
714 }
715
716 if (!(iomod = PyImport_ImportModule("io"))) {
717 goto error;
718 }
719 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
720 goto error;
721 }
722
Georg Brandl1a3284e2007-12-02 09:40:06 +0000723 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000724 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
725 goto error;
726 }
727
Martin v. Löwis0f599892008-06-02 11:13:03 +0000728 encoding = Py_GETENV("PYTHONIOENCODING");
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000729 errors = NULL;
Martin v. Löwis0f599892008-06-02 11:13:03 +0000730 if (encoding) {
731 encoding = strdup(encoding);
732 errors = strchr(encoding, ':');
733 if (errors) {
734 *errors = '\0';
735 errors++;
736 }
737 }
738
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000739 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000740 fd = fileno(stdin);
741 /* Under some conditions stdin, stdout and stderr may not be connected
742 * and fileno() may point to an invalid file descriptor. For example
743 * GUI apps don't have valid standard streams by default.
744 */
745 if (fd < 0) {
746#ifdef MS_WINDOWS
747 std = Py_None;
748 Py_INCREF(std);
749#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000750 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000751#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000752 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000753 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000754 if (!(std = PyFile_FromFd(fd, "<stdin>", "r", -1, encoding,
755 errors, "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000756 goto error;
757 }
758 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000759 PySys_SetObject("__stdin__", std);
760 PySys_SetObject("stdin", std);
761 Py_DECREF(std);
762
763 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000764 fd = fileno(stdout);
765 if (fd < 0) {
766#ifdef MS_WINDOWS
767 std = Py_None;
768 Py_INCREF(std);
769#else
770 goto error;
771#endif
772 }
773 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000774 if (!(std = PyFile_FromFd(fd, "<stdout>", "w", -1, encoding,
775 errors, "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000776 goto error;
777 }
778 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000779 PySys_SetObject("__stdout__", std);
780 PySys_SetObject("stdout", std);
781 Py_DECREF(std);
782
Guido van Rossum98297ee2007-11-06 21:34:58 +0000783#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000784 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000785 fd = fileno(stderr);
786 if (fd < 0) {
787#ifdef MS_WINDOWS
788 std = Py_None;
789 Py_INCREF(std);
790#else
791 goto error;
792#endif
793 }
794 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000795 if (!(std = PyFile_FromFd(fd, "<stderr>", "w", -1, encoding,
Georg Brandl559e5d72008-06-11 18:37:52 +0000796 "backslashreplace", "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000797 goto error;
798 }
799 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000800
801 /* Same as hack above, pre-import stderr's codec to avoid recursion
802 when import.c tries to write to stderr in verbose mode. */
803 encoding_attr = PyObject_GetAttrString(std, "encoding");
804 if (encoding_attr != NULL) {
805 const char * encoding;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000806 encoding = _PyUnicode_AsString(encoding_attr);
Trent Nelson39e307e2008-03-19 06:45:48 +0000807 if (encoding != NULL) {
808 _PyCodec_Lookup(encoding);
809 }
810 }
811 PyErr_Clear(); /* Not a fatal error if codec isn't available */
812
Christian Heimesdb233082007-11-13 02:34:21 +0000813 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000814 PySys_SetObject("stderr", std);
815 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000816#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000817
Christian Heimes58cb1b82007-11-13 02:19:40 +0000818 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000819 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000820 status = -1;
821 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000822
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000823 if (encoding)
824 free(encoding);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000825 Py_XDECREF(bimod);
826 Py_XDECREF(iomod);
827 return status;
828}
829
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000830/* Parse input from a file and execute it */
831
832int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000833PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000834 PyCompilerFlags *flags)
835{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000836 if (filename == NULL)
837 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000838 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000839 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000840 if (closeit)
841 fclose(fp);
842 return err;
843 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000844 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000845 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000846}
847
848int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000849PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000850{
Guido van Rossum82598051997-03-05 00:20:32 +0000851 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000852 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000853 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000854
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000855 if (flags == NULL) {
856 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000857 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000858 }
Guido van Rossum82598051997-03-05 00:20:32 +0000859 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000860 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000861 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000862 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000863 }
Guido van Rossum82598051997-03-05 00:20:32 +0000864 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000865 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000866 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000867 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000868 }
869 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000870 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000871 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000872 if (ret == E_EOF)
873 return 0;
874 /*
875 if (ret == E_NOMEM)
876 return -1;
877 */
878 }
879}
880
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000881/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000882#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000883 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Guido van Rossum45aecf42006-03-15 04:58:47 +0000884 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000885
Thomas Wouters89f507f2006-12-13 04:49:30 +0000886#if 0
887/* Keep an example of flags with future keyword support. */
888#define PARSER_FLAGS(flags) \
889 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
890 PyPARSE_DONT_IMPLY_DEDENT : 0) \
891 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
892 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
893#endif
894
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000895int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000896PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000897{
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000898 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000899 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +0000900 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000901 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000902 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000903
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000904 if (fp == stdin) {
905 /* Fetch encoding from sys.stdin */
906 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +0000907 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000908 return -1;
909 oenc = PyObject_GetAttrString(v, "encoding");
910 if (!oenc)
911 return -1;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000912 enc = _PyUnicode_AsString(oenc);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000913 }
Guido van Rossum82598051997-03-05 00:20:32 +0000914 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000915 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000916 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000917 if (v == NULL)
918 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000919 else if (PyUnicode_Check(v))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000920 ps1 = _PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000921 }
Guido van Rossum82598051997-03-05 00:20:32 +0000922 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000923 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000924 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000925 if (w == NULL)
926 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000927 else if (PyUnicode_Check(w))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000928 ps2 = _PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000929 }
Neal Norwitz9589ee22006-03-04 19:01:22 +0000930 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000931 if (arena == NULL) {
932 Py_XDECREF(v);
933 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000934 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000935 return -1;
936 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000937 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000939 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +0000940 Py_XDECREF(v);
941 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000942 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000943 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000944 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000945 if (errcode == E_EOF) {
946 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000947 return E_EOF;
948 }
Guido van Rossum82598051997-03-05 00:20:32 +0000949 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000950 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000951 }
Guido van Rossum82598051997-03-05 00:20:32 +0000952 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000953 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000954 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000955 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000956 }
Guido van Rossum82598051997-03-05 00:20:32 +0000957 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000958 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +0000959 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +0000960 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000961 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000962 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000963 return -1;
964 }
Guido van Rossum82598051997-03-05 00:20:32 +0000965 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000966 return 0;
967}
968
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000969/* Check whether a file maybe a pyc file: Look at the extension,
970 the file type, and, if we may close it, at the first few bytes. */
971
972static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000973maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000974{
975 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
976 return 1;
977
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000978 /* Only look into the file if we are allowed to close it, since
979 it then should also be seekable. */
980 if (closeit) {
981 /* Read only two bytes of the magic. If the file was opened in
982 text mode, the bytes 3 and 4 of the magic (\r\n) might not
983 be read as they are on disk. */
984 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
985 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +0000986 /* Mess: In case of -x, the stream is NOT at its start now,
987 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000988 which makes the current stream position formally undefined,
989 and a x-platform nightmare.
990 Unfortunately, we have no direct way to know whether -x
991 was specified. So we use a terrible hack: if the current
992 stream position is not 0, we assume -x was specified, and
993 give up. Bug 132850 on SourceForge spells out the
994 hopelessness of trying anything else (fseek and ftell
995 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +0000996 */
Tim Peters3e876562001-02-11 04:35:39 +0000997 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +0000998 if (ftell(fp) == 0) {
999 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001000 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001001 ispyc = 1;
1002 rewind(fp);
1003 }
Tim Peters3e876562001-02-11 04:35:39 +00001004 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001005 }
1006 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001007}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001008
Guido van Rossum0df002c2000-08-27 19:21:52 +00001009int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001010PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001011 PyCompilerFlags *flags)
1012{
Guido van Rossum82598051997-03-05 00:20:32 +00001013 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001014 const char *ext;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001015 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001016
Guido van Rossum82598051997-03-05 00:20:32 +00001017 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001018 if (m == NULL)
1019 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001020 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001021 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001022 PyObject *f;
1023 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001024 if (f == NULL)
1025 return -1;
1026 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1027 Py_DECREF(f);
1028 return -1;
1029 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001030 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001031 Py_DECREF(f);
1032 }
Guido van Rossumfdef2711994-09-14 13:31:04 +00001033 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001034 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001035 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001036 if (closeit)
1037 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001038 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001039 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001040 ret = -1;
1041 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001042 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001043 /* Turn on optimization if a .pyo file is given */
1044 if (strcmp(ext, ".pyo") == 0)
1045 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001046 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001047 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001048 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001049 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001050 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001051 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001052 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001053 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001054 ret = -1;
1055 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001056 }
Guido van Rossum82598051997-03-05 00:20:32 +00001057 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001058 ret = 0;
1059 done:
1060 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1061 PyErr_Clear();
1062 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001063}
1064
1065int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001066PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001067{
Guido van Rossum82598051997-03-05 00:20:32 +00001068 PyObject *m, *d, *v;
1069 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001070 if (m == NULL)
1071 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001072 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001073 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001074 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001075 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001076 return -1;
1077 }
Guido van Rossum82598051997-03-05 00:20:32 +00001078 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001079 return 0;
1080}
1081
Barry Warsaw035574d1997-08-29 22:07:17 +00001082static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001083parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1084 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001085{
1086 long hold;
1087 PyObject *v;
1088
1089 /* old style errors */
1090 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001091 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001092 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001093
1094 /* new style errors. `err' is an instance */
1095
1096 if (! (v = PyObject_GetAttrString(err, "msg")))
1097 goto finally;
1098 *message = v;
1099
1100 if (!(v = PyObject_GetAttrString(err, "filename")))
1101 goto finally;
1102 if (v == Py_None)
1103 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001104 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001105 goto finally;
1106
1107 Py_DECREF(v);
1108 if (!(v = PyObject_GetAttrString(err, "lineno")))
1109 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001110 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001111 Py_DECREF(v);
1112 v = NULL;
1113 if (hold < 0 && PyErr_Occurred())
1114 goto finally;
1115 *lineno = (int)hold;
1116
1117 if (!(v = PyObject_GetAttrString(err, "offset")))
1118 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001119 if (v == Py_None) {
1120 *offset = -1;
1121 Py_DECREF(v);
1122 v = NULL;
1123 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001124 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001125 Py_DECREF(v);
1126 v = NULL;
1127 if (hold < 0 && PyErr_Occurred())
1128 goto finally;
1129 *offset = (int)hold;
1130 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001131
1132 if (!(v = PyObject_GetAttrString(err, "text")))
1133 goto finally;
1134 if (v == Py_None)
1135 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001136 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001137 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001138 goto finally;
1139 Py_DECREF(v);
1140 return 1;
1141
1142finally:
1143 Py_XDECREF(v);
1144 return 0;
1145}
1146
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001147void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001148PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001149{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001150 PyErr_PrintEx(1);
1151}
1152
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001153static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001154print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001155{
1156 char *nl;
1157 if (offset >= 0) {
1158 if (offset > 0 && offset == (int)strlen(text))
1159 offset--;
1160 for (;;) {
1161 nl = strchr(text, '\n');
1162 if (nl == NULL || nl-text >= offset)
1163 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001164 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001165 text = nl+1;
1166 }
1167 while (*text == ' ' || *text == '\t') {
1168 text++;
1169 offset--;
1170 }
1171 }
1172 PyFile_WriteString(" ", f);
1173 PyFile_WriteString(text, f);
1174 if (*text == '\0' || text[strlen(text)-1] != '\n')
1175 PyFile_WriteString("\n", f);
1176 if (offset == -1)
1177 return;
1178 PyFile_WriteString(" ", f);
1179 offset--;
1180 while (offset > 0) {
1181 PyFile_WriteString(" ", f);
1182 offset--;
1183 }
1184 PyFile_WriteString("^\n", f);
1185}
1186
Guido van Rossum66e8e862001-03-23 17:54:43 +00001187static void
1188handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001189{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001190 PyObject *exception, *value, *tb;
1191 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001192
Guido van Rossumd8faa362007-04-27 19:54:29 +00001193 if (Py_InspectFlag)
1194 /* Don't exit if -i flag was given. This flag is set to 0
1195 * when entering interactive mode for inspecting. */
1196 return;
1197
Guido van Rossum66e8e862001-03-23 17:54:43 +00001198 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001199 fflush(stdout);
1200 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001201 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001202 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001203 /* The error code should be in the `code' attribute. */
1204 PyObject *code = PyObject_GetAttrString(value, "code");
1205 if (code) {
1206 Py_DECREF(value);
1207 value = code;
1208 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001209 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001210 }
1211 /* If we failed to dig out the 'code' attribute,
1212 just let the else clause below print the error. */
1213 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001214 if (PyLong_Check(value))
1215 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001216 else {
1217 PyObject_Print(value, stderr, Py_PRINT_RAW);
1218 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001219 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001220 }
Tim Peterscf615b52003-04-19 18:47:02 +00001221 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001222 /* Restore and clear the exception info, in order to properly decref
1223 * the exception, value, and traceback. If we just exit instead,
1224 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1225 * some finalizers from running.
1226 */
Tim Peterscf615b52003-04-19 18:47:02 +00001227 PyErr_Restore(exception, value, tb);
1228 PyErr_Clear();
1229 Py_Exit(exitcode);
1230 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001231}
1232
1233void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001234PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001235{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001236 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001237
1238 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1239 handle_system_exit();
1240 }
Guido van Rossum82598051997-03-05 00:20:32 +00001241 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001242 if (exception == NULL)
1243 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001244 PyErr_NormalizeException(&exception, &v, &tb);
Benjamin Petersone6528212008-07-15 15:32:09 +00001245 tb = tb ? tb : Py_None;
1246 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001247 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001248 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001249 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001250 if (set_sys_last_vars) {
1251 PySys_SetObject("last_type", exception);
1252 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001253 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001254 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001255 hook = PySys_GetObject("excepthook");
1256 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001257 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001258 PyObject *result = PyEval_CallObject(hook, args);
1259 if (result == NULL) {
1260 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001261 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1262 handle_system_exit();
1263 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001264 PyErr_Fetch(&exception2, &v2, &tb2);
1265 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001266 /* It should not be possible for exception2 or v2
1267 to be NULL. However PyErr_Display() can't
1268 tolerate NULLs, so just be safe. */
1269 if (exception2 == NULL) {
1270 exception2 = Py_None;
1271 Py_INCREF(exception2);
1272 }
1273 if (v2 == NULL) {
1274 v2 = Py_None;
1275 Py_INCREF(v2);
1276 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001277 fflush(stdout);
1278 PySys_WriteStderr("Error in sys.excepthook:\n");
1279 PyErr_Display(exception2, v2, tb2);
1280 PySys_WriteStderr("\nOriginal exception was:\n");
1281 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001282 Py_DECREF(exception2);
1283 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001284 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001285 }
1286 Py_XDECREF(result);
1287 Py_XDECREF(args);
1288 } else {
1289 PySys_WriteStderr("sys.excepthook is missing\n");
1290 PyErr_Display(exception, v, tb);
1291 }
1292 Py_XDECREF(exception);
1293 Py_XDECREF(v);
1294 Py_XDECREF(tb);
1295}
1296
Benjamin Petersone6528212008-07-15 15:32:09 +00001297static void
1298print_exception(PyObject *f, PyObject *value)
1299{
1300 int err = 0;
1301 PyObject *type, *tb;
1302
Benjamin Peterson26582602008-08-23 20:08:07 +00001303 if (!PyExceptionInstance_Check(value)) {
1304 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1305 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1306 PyFile_WriteString(" found\n", f);
1307 return;
1308 }
1309
Benjamin Petersone6528212008-07-15 15:32:09 +00001310 Py_INCREF(value);
1311 fflush(stdout);
1312 type = (PyObject *) Py_TYPE(value);
1313 tb = PyException_GetTraceback(value);
1314 if (tb && tb != Py_None)
1315 err = PyTraceBack_Print(tb, f);
1316 if (err == 0 &&
1317 PyObject_HasAttrString(value, "print_file_and_line"))
1318 {
1319 PyObject *message;
1320 const char *filename, *text;
1321 int lineno, offset;
1322 if (!parse_syntax_error(value, &message, &filename,
1323 &lineno, &offset, &text))
1324 PyErr_Clear();
1325 else {
1326 char buf[10];
1327 PyFile_WriteString(" File \"", f);
1328 if (filename == NULL)
1329 PyFile_WriteString("<string>", f);
1330 else
1331 PyFile_WriteString(filename, f);
1332 PyFile_WriteString("\", line ", f);
1333 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1334 PyFile_WriteString(buf, f);
1335 PyFile_WriteString("\n", f);
1336 if (text != NULL)
1337 print_error_text(f, offset, text);
1338 Py_DECREF(value);
1339 value = message;
1340 /* Can't be bothered to check all those
1341 PyFile_WriteString() calls */
1342 if (PyErr_Occurred())
1343 err = -1;
1344 }
1345 }
1346 if (err) {
1347 /* Don't do anything else */
1348 }
1349 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001350 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001351 char* className;
1352 assert(PyExceptionClass_Check(type));
1353 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001354 if (className != NULL) {
1355 char *dot = strrchr(className, '.');
1356 if (dot != NULL)
1357 className = dot+1;
1358 }
1359
1360 moduleName = PyObject_GetAttrString(type, "__module__");
1361 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1362 {
1363 Py_DECREF(moduleName);
1364 err = PyFile_WriteString("<unknown>", f);
1365 }
1366 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001367 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001368 if (modstr && strcmp(modstr, "builtins"))
1369 {
1370 err = PyFile_WriteString(modstr, f);
1371 err += PyFile_WriteString(".", f);
1372 }
1373 Py_DECREF(moduleName);
1374 }
1375 if (err == 0) {
1376 if (className == NULL)
1377 err = PyFile_WriteString("<unknown>", f);
1378 else
1379 err = PyFile_WriteString(className, f);
1380 }
1381 }
1382 if (err == 0 && (value != Py_None)) {
1383 PyObject *s = PyObject_Str(value);
1384 /* only print colon if the str() of the
1385 object is not the empty string
1386 */
1387 if (s == NULL)
1388 err = -1;
1389 else if (!PyUnicode_Check(s) ||
1390 PyUnicode_GetSize(s) != 0)
1391 err = PyFile_WriteString(": ", f);
1392 if (err == 0)
1393 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1394 Py_XDECREF(s);
1395 }
1396 /* try to write a newline in any case */
1397 err += PyFile_WriteString("\n", f);
1398 Py_XDECREF(tb);
1399 Py_DECREF(value);
1400 /* If an error happened here, don't show it.
1401 XXX This is wrong, but too many callers rely on this behavior. */
1402 if (err != 0)
1403 PyErr_Clear();
1404}
1405
1406static const char *cause_message =
1407 "\nThe above exception was the direct cause "
1408 "of the following exception:\n\n";
1409
1410static const char *context_message =
1411 "\nDuring handling of the above exception, "
1412 "another exception occurred:\n\n";
1413
1414static void
1415print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1416{
1417 int err = 0, res;
1418 PyObject *cause, *context;
1419
1420 if (seen != NULL) {
1421 /* Exception chaining */
1422 if (PySet_Add(seen, value) == -1)
1423 PyErr_Clear();
1424 else if (PyExceptionInstance_Check(value)) {
1425 cause = PyException_GetCause(value);
1426 context = PyException_GetContext(value);
1427 if (cause) {
1428 res = PySet_Contains(seen, cause);
1429 if (res == -1)
1430 PyErr_Clear();
1431 if (res == 0) {
1432 print_exception_recursive(
1433 f, cause, seen);
1434 err |= PyFile_WriteString(
1435 cause_message, f);
1436 }
1437 }
1438 if (context) {
1439 res = PySet_Contains(seen, context);
1440 if (res == -1)
1441 PyErr_Clear();
1442 if (res == 0) {
1443 print_exception_recursive(
1444 f, context, seen);
1445 err |= PyFile_WriteString(
1446 context_message, f);
1447 }
1448 }
1449 Py_XDECREF(context);
1450 Py_XDECREF(cause);
1451 }
1452 }
1453 print_exception(f, value);
1454 if (err != 0)
1455 PyErr_Clear();
1456}
1457
Thomas Wouters477c8d52006-05-27 19:21:47 +00001458void
1459PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001460{
Benjamin Petersone6528212008-07-15 15:32:09 +00001461 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001462 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001463 if (f == Py_None) {
1464 /* pass */
1465 }
1466 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001467 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001468 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001469 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001470 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001471 /* We choose to ignore seen being possibly NULL, and report
1472 at least the main exception (it could be a MemoryError).
1473 */
1474 seen = PySet_New(NULL);
1475 if (seen == NULL)
1476 PyErr_Clear();
1477 print_exception_recursive(f, value, seen);
1478 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001479 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001480}
1481
Guido van Rossum82598051997-03-05 00:20:32 +00001482PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001483PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001484 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001485{
Neal Norwitze92fba02006-03-04 18:52:26 +00001486 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001487 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001488 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001489 if (arena == NULL)
1490 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001491
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001492 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001493 if (mod != NULL)
1494 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001495 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001497}
1498
1499PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001500PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001501 PyObject *locals, int closeit, PyCompilerFlags *flags)
1502{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001503 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001504 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001505 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001506 if (arena == NULL)
1507 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001508
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001509 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001510 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001511 if (closeit)
1512 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001513 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001514 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001515 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001516 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001517 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001518 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001519 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001520}
1521
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001522static void
1523flush_io(void)
1524{
1525 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001526 PyObject *type, *value, *traceback;
1527
1528 /* Save the current exception */
1529 PyErr_Fetch(&type, &value, &traceback);
1530
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001531 f = PySys_GetObject("stderr");
1532 if (f != NULL) {
1533 r = PyObject_CallMethod(f, "flush", "");
1534 if (r)
1535 Py_DECREF(r);
1536 else
1537 PyErr_Clear();
1538 }
1539 f = PySys_GetObject("stdout");
1540 if (f != NULL) {
1541 r = PyObject_CallMethod(f, "flush", "");
1542 if (r)
1543 Py_DECREF(r);
1544 else
1545 PyErr_Clear();
1546 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001547
1548 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001549}
1550
Guido van Rossum82598051997-03-05 00:20:32 +00001551static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001552run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001553 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001554{
Guido van Rossum82598051997-03-05 00:20:32 +00001555 PyCodeObject *co;
1556 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001557 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001558 if (co == NULL)
1559 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001560 v = PyEval_EvalCode(co, globals, locals);
1561 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001562 return v;
1563}
1564
Guido van Rossum82598051997-03-05 00:20:32 +00001565static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001566run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001567 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001568{
Guido van Rossum82598051997-03-05 00:20:32 +00001569 PyCodeObject *co;
1570 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001571 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001572 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001573
Guido van Rossum82598051997-03-05 00:20:32 +00001574 magic = PyMarshal_ReadLongFromFile(fp);
1575 if (magic != PyImport_GetMagicNumber()) {
1576 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001577 "Bad magic number in .pyc file");
1578 return NULL;
1579 }
Guido van Rossum82598051997-03-05 00:20:32 +00001580 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001581 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001582 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001583 if (v == NULL || !PyCode_Check(v)) {
1584 Py_XDECREF(v);
1585 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001586 "Bad code object in .pyc file");
1587 return NULL;
1588 }
Guido van Rossum82598051997-03-05 00:20:32 +00001589 co = (PyCodeObject *)v;
1590 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001591 if (v && flags)
1592 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001593 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001594 return v;
1595}
1596
Guido van Rossum82598051997-03-05 00:20:32 +00001597PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001598Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001599 PyCompilerFlags *flags)
1600{
Guido van Rossum82598051997-03-05 00:20:32 +00001601 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001602 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001603 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001604 if (arena == NULL)
1605 return NULL;
1606
1607 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001608 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001609 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001610 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001611 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001612 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001613 PyObject *result = PyAST_mod2obj(mod);
1614 PyArena_Free(arena);
1615 return result;
1616 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001617 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001618 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001619 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001620}
1621
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001622struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001623Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001624{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001625 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001626 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001627 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001628 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001629 if (arena == NULL)
1630 return NULL;
1631
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001632 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001633 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001634 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001635 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001636 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001637 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001638 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001639 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001640 return st;
1641}
1642
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001643/* Preferred access to parser is through AST. */
1644mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001645PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001646 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001647{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001648 mod_ty mod;
1649 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001650 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001651
1652 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001653 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001654 &iflags);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001655 if (n) {
Christian Heimes4d6ec852008-03-26 22:34:47 +00001656 if (flags) {
1657 flags->cf_flags |= iflags & PyCF_MASK;
1658 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001659 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001660 PyNode_Free(n);
1661 return mod;
1662 }
1663 else {
1664 err_input(&err);
1665 return NULL;
1666 }
1667}
1668
1669mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001670PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1671 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001672 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001673 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001674{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001675 mod_ty mod;
1676 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001677 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001678
Christian Heimes4d6ec852008-03-26 22:34:47 +00001679 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001680 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001681 start, ps1, ps2, &err, &iflags);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001682 if (n) {
Christian Heimes4d6ec852008-03-26 22:34:47 +00001683 if (flags) {
1684 flags->cf_flags |= iflags & PyCF_MASK;
1685 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001686 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001687 PyNode_Free(n);
1688 return mod;
1689 }
1690 else {
1691 err_input(&err);
1692 if (errcode)
1693 *errcode = err.error;
1694 return NULL;
1695 }
1696}
1697
Guido van Rossuma110aa61994-08-29 12:50:44 +00001698/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001699
Guido van Rossuma110aa61994-08-29 12:50:44 +00001700node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001701PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001702{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001703 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001704 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1705 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001706 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001707 if (n == NULL)
1708 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001709
Guido van Rossuma110aa61994-08-29 12:50:44 +00001710 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001711}
1712
Guido van Rossuma110aa61994-08-29 12:50:44 +00001713/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001714
Guido van Rossuma110aa61994-08-29 12:50:44 +00001715node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001716PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001717{
Tim Petersfe2127d2001-07-16 05:37:24 +00001718 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001719 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1720 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001721 if (n == NULL)
1722 err_input(&err);
1723 return n;
1724}
1725
1726node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001727PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001728 int start, int flags)
1729{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001730 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001731 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1732 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001733 if (n == NULL)
1734 err_input(&err);
1735 return n;
1736}
1737
1738node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001739PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001740{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001741 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001742}
1743
Guido van Rossum66ebd912003-04-17 16:02:26 +00001744/* May want to move a more generalized form of this to parsetok.c or
1745 even parser modules. */
1746
1747void
1748PyParser_SetError(perrdetail *err)
1749{
1750 err_input(err);
1751}
1752
Guido van Rossuma110aa61994-08-29 12:50:44 +00001753/* Set the error appropriate to the given input error code (see errcode.h) */
1754
1755static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001756err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001757{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001758 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001759 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001760 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001761 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001762 switch (err->error) {
1763 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001764 errtype = PyExc_IndentationError;
1765 if (err->expected == INDENT)
1766 msg = "expected an indented block";
1767 else if (err->token == INDENT)
1768 msg = "unexpected indent";
1769 else if (err->token == DEDENT)
1770 msg = "unexpected unindent";
1771 else {
1772 errtype = PyExc_SyntaxError;
1773 msg = "invalid syntax";
1774 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001775 break;
1776 case E_TOKEN:
1777 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001778 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001779 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001780 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001781 break;
1782 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001783 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001784 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001785 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001786 if (!PyErr_Occurred())
1787 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001788 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001789 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001790 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001791 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001792 case E_EOF:
1793 msg = "unexpected EOF while parsing";
1794 break;
Fred Drake85f36392000-07-11 17:53:00 +00001795 case E_TABSPACE:
1796 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001797 msg = "inconsistent use of tabs and spaces in indentation";
1798 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001799 case E_OVERFLOW:
1800 msg = "expression too long";
1801 break;
Fred Drake85f36392000-07-11 17:53:00 +00001802 case E_DEDENT:
1803 errtype = PyExc_IndentationError;
1804 msg = "unindent does not match any outer indentation level";
1805 break;
1806 case E_TOODEEP:
1807 errtype = PyExc_IndentationError;
1808 msg = "too many levels of indentation";
1809 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001810 case E_DECODE: {
1811 PyObject *type, *value, *tb;
1812 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001813 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001814 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001815 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001816 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001817 }
1818 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001819 if (msg == NULL)
1820 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001821 Py_XDECREF(type);
1822 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001823 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001824 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001825 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001826 case E_LINECONT:
1827 msg = "unexpected character after line continuation character";
1828 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001829
1830 case E_IDENTIFIER:
1831 msg = "invalid character in identifier";
1832 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001833 default:
1834 fprintf(stderr, "error=%d\n", err->error);
1835 msg = "unknown parsing error";
1836 break;
1837 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001838 /* err->text may not be UTF-8 in case of decoding errors.
1839 Explicitly convert to an object. */
1840 if (!err->text) {
1841 errtext = Py_None;
1842 Py_INCREF(Py_None);
1843 } else {
1844 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1845 "replace");
1846 }
1847 v = Py_BuildValue("(ziiN)", err->filename,
1848 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001849 w = NULL;
1850 if (v != NULL)
1851 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001852 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001853 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001854 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001855 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001856cleanup:
1857 if (err->text != NULL) {
1858 PyObject_FREE(err->text);
1859 err->text = NULL;
1860 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001861}
1862
1863/* Print fatal error message and abort */
1864
1865void
Tim Peters7c321a82002-07-09 02:57:01 +00001866Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001867{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001868 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001869 if (PyErr_Occurred()) {
1870 PyErr_Print();
1871 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001872#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001873 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001874 OutputDebugString(msg);
1875 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001876#ifdef _DEBUG
1877 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001878#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001879#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001880 abort();
1881}
1882
1883/* Clean up and exit */
1884
Guido van Rossuma110aa61994-08-29 12:50:44 +00001885#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001886#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001887#endif
1888
Collin Winter670e6922007-03-21 02:57:17 +00001889static void (*pyexitfunc)(void) = NULL;
1890/* For the atexit module. */
1891void _Py_PyAtExit(void (*func)(void))
1892{
1893 pyexitfunc = func;
1894}
1895
1896static void
1897call_py_exitfuncs(void)
1898{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001899 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00001900 return;
1901
1902 (*pyexitfunc)();
1903 PyErr_Clear();
1904}
1905
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001906#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001907static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001908static int nexitfuncs = 0;
1909
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001910int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001911{
1912 if (nexitfuncs >= NEXITFUNCS)
1913 return -1;
1914 exitfuncs[nexitfuncs++] = func;
1915 return 0;
1916}
1917
Guido van Rossumcc283f51997-08-05 02:22:03 +00001918static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001919call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001920{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001921 while (nexitfuncs > 0)
1922 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001923
1924 fflush(stdout);
1925 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001926}
1927
1928void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001929Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001930{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001931 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001932
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001933 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001934}
1935
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001936static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001937initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001938{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001939#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001940 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001941#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001942#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001943 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001944#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001945#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001946 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001947#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001948 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001949}
1950
Guido van Rossum7433b121997-02-14 19:45:36 +00001951
1952/*
1953 * The file descriptor fd is considered ``interactive'' if either
1954 * a) isatty(fd) is TRUE, or
1955 * b) the -i flag was given, and the filename associated with
1956 * the descriptor is NULL or "<stdin>" or "???".
1957 */
1958int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001959Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001960{
1961 if (isatty((int)fileno(fp)))
1962 return 1;
1963 if (!Py_InteractiveFlag)
1964 return 0;
1965 return (filename == NULL) ||
1966 (strcmp(filename, "<stdin>") == 0) ||
1967 (strcmp(filename, "???") == 0);
1968}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001969
1970
Tim Petersd08e3822003-04-17 15:24:21 +00001971#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001972#if defined(WIN32) && defined(_MSC_VER)
1973
1974/* Stack checking for Microsoft C */
1975
1976#include <malloc.h>
1977#include <excpt.h>
1978
Fred Drakee8de31c2000-08-31 05:38:39 +00001979/*
1980 * Return non-zero when we run out of memory on the stack; zero otherwise.
1981 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001982int
Fred Drake399739f2000-08-31 05:52:44 +00001983PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001984{
1985 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001986 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001987 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001988 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001989 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00001990 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00001991 EXCEPTION_EXECUTE_HANDLER :
1992 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00001993 int errcode = _resetstkoflw();
1994 if (errcode)
1995 {
1996 Py_FatalError("Could not reset the stack!");
1997 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001998 }
1999 return 1;
2000}
2001
2002#endif /* WIN32 && _MSC_VER */
2003
2004/* Alternate implementations can be added here... */
2005
2006#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002007
2008
2009/* Wrappers around sigaction() or signal(). */
2010
2011PyOS_sighandler_t
2012PyOS_getsig(int sig)
2013{
2014#ifdef HAVE_SIGACTION
2015 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002016 if (sigaction(sig, NULL, &context) == -1)
2017 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002018 return context.sa_handler;
2019#else
2020 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002021/* Special signal handling for the secure CRT in Visual Studio 2005 */
2022#if defined(_MSC_VER) && _MSC_VER >= 1400
2023 switch (sig) {
2024 /* Only these signals are valid */
2025 case SIGINT:
2026 case SIGILL:
2027 case SIGFPE:
2028 case SIGSEGV:
2029 case SIGTERM:
2030 case SIGBREAK:
2031 case SIGABRT:
2032 break;
2033 /* Don't call signal() with other values or it will assert */
2034 default:
2035 return SIG_ERR;
2036 }
2037#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002038 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002039 if (handler != SIG_ERR)
2040 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002041 return handler;
2042#endif
2043}
2044
2045PyOS_sighandler_t
2046PyOS_setsig(int sig, PyOS_sighandler_t handler)
2047{
2048#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002049 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002050 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002051 sigemptyset(&context.sa_mask);
2052 context.sa_flags = 0;
2053 if (sigaction(sig, &context, &ocontext) == -1)
2054 return SIG_ERR;
2055 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002056#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002057 PyOS_sighandler_t oldhandler;
2058 oldhandler = signal(sig, handler);
2059#ifdef HAVE_SIGINTERRUPT
2060 siginterrupt(sig, 1);
2061#endif
2062 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002063#endif
2064}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002065
2066/* Deprecated C API functions still provided for binary compatiblity */
2067
2068#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002069PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002070PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2071{
2072 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2073}
2074
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002075#undef PyParser_SimpleParseString
2076PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002077PyParser_SimpleParseString(const char *str, int start)
2078{
2079 return PyParser_SimpleParseStringFlags(str, start, 0);
2080}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002081
2082#undef PyRun_AnyFile
2083PyAPI_FUNC(int)
2084PyRun_AnyFile(FILE *fp, const char *name)
2085{
2086 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2087}
2088
2089#undef PyRun_AnyFileEx
2090PyAPI_FUNC(int)
2091PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2092{
2093 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2094}
2095
2096#undef PyRun_AnyFileFlags
2097PyAPI_FUNC(int)
2098PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2099{
2100 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2101}
2102
2103#undef PyRun_File
2104PyAPI_FUNC(PyObject *)
2105PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2106{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002107 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002108}
2109
2110#undef PyRun_FileEx
2111PyAPI_FUNC(PyObject *)
2112PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2113{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002114 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002115}
2116
2117#undef PyRun_FileFlags
2118PyAPI_FUNC(PyObject *)
2119PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2120 PyCompilerFlags *flags)
2121{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002122 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002123}
2124
2125#undef PyRun_SimpleFile
2126PyAPI_FUNC(int)
2127PyRun_SimpleFile(FILE *f, const char *p)
2128{
2129 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2130}
2131
2132#undef PyRun_SimpleFileEx
2133PyAPI_FUNC(int)
2134PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2135{
2136 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2137}
2138
2139
2140#undef PyRun_String
2141PyAPI_FUNC(PyObject *)
2142PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2143{
2144 return PyRun_StringFlags(str, s, g, l, NULL);
2145}
2146
2147#undef PyRun_SimpleString
2148PyAPI_FUNC(int)
2149PyRun_SimpleString(const char *s)
2150{
2151 return PyRun_SimpleStringFlags(s, NULL);
2152}
2153
2154#undef Py_CompileString
2155PyAPI_FUNC(PyObject *)
2156Py_CompileString(const char *str, const char *p, int s)
2157{
2158 return Py_CompileStringFlags(str, p, s, NULL);
2159}
2160
2161#undef PyRun_InteractiveOne
2162PyAPI_FUNC(int)
2163PyRun_InteractiveOne(FILE *f, const char *p)
2164{
2165 return PyRun_InteractiveOneFlags(f, p, NULL);
2166}
2167
2168#undef PyRun_InteractiveLoop
2169PyAPI_FUNC(int)
2170PyRun_InteractiveLoop(FILE *f, const char *p)
2171{
2172 return PyRun_InteractiveLoopFlags(f, p, NULL);
2173}
2174
2175#ifdef __cplusplus
2176}
2177#endif