blob: c5f7e23adcf6e8ab737b38ef0d4972fafef1f9e3 [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
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000026#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000027#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000028#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000029
Martin v. Löwis73d538b2003-03-05 15:13:47 +000030#ifdef HAVE_LANGINFO_H
31#include <locale.h>
32#include <langinfo.h>
33#endif
34
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000035#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#undef BYTE
37#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000038#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000039#endif
40
Neal Norwitz4281cef2006-03-04 19:58:13 +000041#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000042#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000043#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#define PRINT_TOTAL_REFS() fprintf(stderr, \
45 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
46 _Py_GetRefTotal())
47#endif
48
49#ifdef __cplusplus
50extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000051#endif
52
Martin v. Löwis790465f2008-04-05 20:41:37 +000053extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000054
Guido van Rossum82598051997-03-05 00:20:32 +000055extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000056
Guido van Rossumb73cc041993-11-01 16:28:59 +000057/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000058static void initmain(void);
59static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000060static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000061static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000062static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000063 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000064static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000065 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void err_input(perrdetail *);
67static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000068static void call_py_exitfuncs(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000069static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000070extern void _PyUnicode_Init(void);
71extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000074
Mark Hammond8d98d2c2003-04-19 15:41:53 +000075#ifdef WITH_THREAD
76extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
78#endif /* WITH_THREAD */
79
Guido van Rossum82598051997-03-05 00:20:32 +000080int Py_DebugFlag; /* Needed by parser.c */
81int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000082int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000083int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000084int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000085int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000086int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000087int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000088int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000089int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000090int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000091
Christian Heimes33fe8092008-04-13 13:53:33 +000092/* PyModule_GetWarningsModule is no longer necessary as of 2.6
93since _warnings is builtin. This API should not be used. */
94PyObject *
95PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000096{
Christian Heimes33fe8092008-04-13 13:53:33 +000097 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000098}
Mark Hammonda43fd0c2003-02-19 00:33:33 +000099
Guido van Rossum25ce5661997-08-02 03:10:38 +0000100static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000101
Thomas Wouters7e474022000-07-16 12:04:32 +0000102/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000103
104int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000105Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106{
107 return initialized;
108}
109
Guido van Rossum25ce5661997-08-02 03:10:38 +0000110/* Global initializations. Can be undone by Py_Finalize(). Don't
111 call this twice without an intervening Py_Finalize() call. When
112 initializations fail, a fatal error is issued and the function does
113 not return. On return, the first thread and interpreter state have
114 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000115
Guido van Rossum25ce5661997-08-02 03:10:38 +0000116 Locking: you must hold the interpreter lock while calling this.
117 (If the lock has not yet been initialized, that's equivalent to
118 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000119
Guido van Rossum25ce5661997-08-02 03:10:38 +0000120*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000121
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000122static int
123add_flag(int flag, const char *envs)
124{
125 int env = atoi(envs);
126 if (flag < env)
127 flag = env;
128 if (flag < 1)
129 flag = 1;
130 return flag;
131}
132
Christian Heimes5833a2f2008-10-30 21:40:04 +0000133#if defined(HAVE_LANGINFO_H) && defined(CODESET)
134static char*
135get_codeset(void)
136{
137 char* codeset;
138 PyObject *codec, *name;
139
140 codeset = nl_langinfo(CODESET);
141 if (!codeset || codeset[0] == '\0')
142 return NULL;
143
144 codec = _PyCodec_Lookup(codeset);
145 if (!codec)
146 goto error;
147
148 name = PyObject_GetAttrString(codec, "name");
149 Py_CLEAR(codec);
150 if (!name)
151 goto error;
152
153 codeset = strdup(_PyUnicode_AsString(name));
154 Py_DECREF(name);
155 return codeset;
156
157error:
158 Py_XDECREF(codec);
159 PyErr_Clear();
160 return NULL;
161}
162#endif
163
Guido van Rossuma027efa1997-05-05 20:56:21 +0000164void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000165Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000166{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000168 PyThreadState *tstate;
Guido van Rossum826d8972007-10-30 18:34:07 +0000169 PyObject *bimod, *sysmod, *pstderr;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000170 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000171#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000172 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000173#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000174 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000175
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000176 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000177 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000178 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000179
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000180#ifdef HAVE_SETLOCALE
181 /* Set up the LC_CTYPE locale, so we can obtain
182 the locale's charset without having to switch
183 locales. */
184 setlocale(LC_CTYPE, "");
185#endif
186
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000187 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000188 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000189 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000190 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000191 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000192 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Christian Heimes790c8232008-01-07 21:14:23 +0000193 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
194 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000195
Guido van Rossuma027efa1997-05-05 20:56:21 +0000196 interp = PyInterpreterState_New();
197 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000198 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000199
Guido van Rossuma027efa1997-05-05 20:56:21 +0000200 tstate = PyThreadState_New(interp);
201 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000203 (void) PyThreadState_Swap(tstate);
204
Guido van Rossum70d893a2001-08-16 08:21:42 +0000205 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000206
Neal Norwitzb2501f42002-12-31 03:42:13 +0000207 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000208 Py_FatalError("Py_Initialize: can't init frames");
209
Guido van Rossumddefaf32007-01-14 03:31:43 +0000210 if (!_PyLong_Init())
211 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000212
Christian Heimes9c4756e2008-05-26 13:22:05 +0000213 if (!PyByteArray_Init())
Neal Norwitz6968b052007-02-27 19:02:19 +0000214 Py_FatalError("Py_Initialize: can't init bytes");
215
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000216 _PyFloat_Init();
217
Guido van Rossum25ce5661997-08-02 03:10:38 +0000218 interp->modules = PyDict_New();
219 if (interp->modules == NULL)
220 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000221 interp->modules_reloading = PyDict_New();
222 if (interp->modules_reloading == NULL)
223 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000224
Guido van Rossumc94044c2000-03-10 23:03:54 +0000225 /* Init Unicode implementation; relies on the codec registry */
226 _PyUnicode_Init();
227
Barry Warsawf242aa02000-05-25 23:09:49 +0000228 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000229 if (bimod == NULL)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000230 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Martin v. Löwis1a214512008-06-11 05:26:20 +0000231 _PyImport_FixupExtension(bimod, "builtins", "builtins");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000232 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000233 if (interp->builtins == NULL)
234 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000235 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000236
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000237 /* initialize builtin exceptions */
238 _PyExc_Init();
239
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240 sysmod = _PySys_Init();
241 if (sysmod == NULL)
242 Py_FatalError("Py_Initialize: can't initialize sys");
243 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000244 if (interp->sysdict == NULL)
245 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000246 Py_INCREF(interp->sysdict);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000247 _PyImport_FixupExtension(sysmod, "sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000248 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000249 PyDict_SetItemString(interp->sysdict, "modules",
250 interp->modules);
251
Guido van Rossum826d8972007-10-30 18:34:07 +0000252 /* Set up a preliminary stderr printer until we have enough
253 infrastructure for the io module in place. */
254 pstderr = PyFile_NewStdPrinter(fileno(stderr));
255 if (pstderr == NULL)
256 Py_FatalError("Py_Initialize: can't set preliminary stderr");
257 PySys_SetObject("stderr", pstderr);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000258 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000259
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000260 _PyImport_Init();
261
Just van Rossum52e14d62002-12-30 22:08:05 +0000262 _PyImportHooks_Init();
263
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000264 if (install_sigs)
265 initsigs(); /* Signal handling stuff, including initintr() */
Christian Heimes33fe8092008-04-13 13:53:33 +0000266
Georg Brandl86b2fb92008-07-16 03:43:04 +0000267 /* Initialize warnings. */
268 _PyWarnings_Init();
269 if (PySys_HasWarnOptions()) {
270 PyObject *warnings_module = PyImport_ImportModule("warnings");
271 if (!warnings_module)
272 PyErr_Clear();
273 Py_XDECREF(warnings_module);
274 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275
276 initmain(); /* Module __main__ */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000277 if (initstdio() < 0)
278 Py_FatalError(
279 "Py_Initialize: can't initialize sys standard streams");
Benjamin Peterson791dc2f2008-09-05 23:27:15 +0000280 if (!Py_NoSiteFlag)
281 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000282
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000283 /* auto-thread-state API, if available */
284#ifdef WITH_THREAD
285 _PyGILState_Init(interp, tstate);
286#endif /* WITH_THREAD */
287
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000288#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000289 /* On Unix, set the file system encoding according to the
290 user's preference, if the CODESET names a well-known
291 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000292 initialized by other means. Also set the encoding of
293 stdin and stdout if these are terminals. */
294
Christian Heimes5833a2f2008-10-30 21:40:04 +0000295 codeset = get_codeset();
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000296 if (codeset) {
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000297 if (!Py_FileSystemDefaultEncoding)
298 Py_FileSystemDefaultEncoding = codeset;
299 else
300 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000301 }
302#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000303}
304
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000305void
306Py_Initialize(void)
307{
308 Py_InitializeEx(1);
309}
310
311
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000312#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000313extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000314#endif
315
Guido van Rossume8432ac2007-07-09 15:04:50 +0000316/* Flush stdout and stderr */
317
Neal Norwitz2bad9702007-08-27 06:19:22 +0000318static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000319flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000320{
321 PyObject *fout = PySys_GetObject("stdout");
322 PyObject *ferr = PySys_GetObject("stderr");
323 PyObject *tmp;
324
Christian Heimes2be03732007-11-15 02:26:46 +0000325 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000326 tmp = PyObject_CallMethod(fout, "flush", "");
327 if (tmp == NULL)
328 PyErr_Clear();
329 else
330 Py_DECREF(tmp);
331 }
332
Christian Heimes2be03732007-11-15 02:26:46 +0000333 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000334 tmp = PyObject_CallMethod(ferr, "flush", "");
335 if (tmp == NULL)
336 PyErr_Clear();
337 else
338 Py_DECREF(tmp);
339 }
340}
341
Guido van Rossum25ce5661997-08-02 03:10:38 +0000342/* Undo the effect of Py_Initialize().
343
344 Beware: if multiple interpreter and/or thread states exist, these
345 are not wiped out; only the current thread and interpreter state
346 are deleted. But since everything else is deleted, those other
347 interpreter and thread states should no longer be used.
348
349 (XXX We should do better, e.g. wipe out all interpreters and
350 threads.)
351
352 Locking: as above.
353
354*/
355
356void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000357Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000358{
359 PyInterpreterState *interp;
360 PyThreadState *tstate;
361
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000362 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000363 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000364
Tim Peters384fd102001-01-21 03:40:37 +0000365 /* The interpreter is still entirely intact at this point, and the
366 * exit funcs may be relying on that. In particular, if some thread
367 * or exit func is still waiting to do an import, the import machinery
368 * expects Py_IsInitialized() to return true. So don't say the
369 * interpreter is uninitialized until after the exit funcs have run.
370 * Note that Threading.py uses an exit func to do a join on all the
371 * threads created thru it, so this also protects pending imports in
372 * the threads created via Threading.
373 */
Collin Winter670e6922007-03-21 02:57:17 +0000374 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000375 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000376
Guido van Rossume8432ac2007-07-09 15:04:50 +0000377 /* Flush stdout+stderr */
378 flush_std_files();
379
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000380 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000381 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000382 interp = tstate->interp;
383
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000384 /* Disable signal handling */
385 PyOS_FiniInterrupts();
386
Christian Heimes26855632008-01-27 23:50:43 +0000387 /* Clear type lookup cache */
388 PyType_ClearCache();
389
Guido van Rossume13ddc92003-04-17 17:29:22 +0000390 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000391 * before all modules are destroyed.
392 * XXX If a __del__ or weakref callback is triggered here, and tries to
393 * XXX import a module, bad things can happen, because Python no
394 * XXX longer believes it's initialized.
395 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
396 * XXX is easy to provoke that way. I've also seen, e.g.,
397 * XXX Exception exceptions.ImportError: 'No module named sha'
398 * XXX in <function callback at 0x008F5718> ignored
399 * XXX but I'm unclear on exactly how that one happens. In any case,
400 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000401 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000402 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000403#ifdef COUNT_ALLOCS
404 /* With COUNT_ALLOCS, it helps to run GC multiple times:
405 each collection might release some types from the type
406 list, so they become garbage. */
407 while (PyGC_Collect() > 0)
408 /* nothing */;
409#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000410
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000411 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000412 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000413
Guido van Rossume8432ac2007-07-09 15:04:50 +0000414 /* Flush stdout+stderr (again, in case more was printed) */
415 flush_std_files();
416
Guido van Rossume13ddc92003-04-17 17:29:22 +0000417 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000418 * new-style class definitions, for example.
419 * XXX This is disabled because it caused too many problems. If
420 * XXX a __del__ or weakref callback triggers here, Python code has
421 * XXX a hard time running, because even the sys module has been
422 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
423 * XXX One symptom is a sequence of information-free messages
424 * XXX coming from threads (if a __del__ or callback is invoked,
425 * XXX other threads can execute too, and any exception they encounter
426 * XXX triggers a comedy of errors as subsystem after subsystem
427 * XXX fails to find what it *expects* to find in sys to help report
428 * XXX the exception and consequent unexpected failures). I've also
429 * XXX seen segfaults then, after adding print statements to the
430 * XXX Python code getting called.
431 */
432#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000433 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000434#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000435
Guido van Rossum1707aad1997-12-08 23:43:45 +0000436 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
437 _PyImport_Fini();
438
439 /* Debugging stuff */
440#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000441 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000442#endif
443
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000444 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000445
Tim Peters9cf25ce2003-04-17 15:21:01 +0000446#ifdef Py_TRACE_REFS
447 /* Display all objects still alive -- this can invoke arbitrary
448 * __repr__ overrides, so requires a mostly-intact interpreter.
449 * Alas, a lot of stuff may still be alive now that will be cleaned
450 * up later.
451 */
Tim Peters269b2a62003-04-17 19:52:29 +0000452 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000453 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000454#endif /* Py_TRACE_REFS */
455
Guido van Rossumd922fa42003-04-15 14:10:09 +0000456 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000457 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000458
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000459 /* Now we decref the exception classes. After this point nothing
460 can raise an exception. That's okay, because each Fini() method
461 below has been checked to make sure no exceptions are ever
462 raised.
463 */
464
465 _PyExc_Fini();
466
Christian Heimes7d2ff882007-11-30 14:35:04 +0000467 /* Cleanup auto-thread-state */
468#ifdef WITH_THREAD
469 _PyGILState_Fini();
470#endif /* WITH_THREAD */
471
Guido van Rossumd922fa42003-04-15 14:10:09 +0000472 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000473 PyThreadState_Swap(NULL);
474 PyInterpreterState_Delete(interp);
475
Guido van Rossumd922fa42003-04-15 14:10:09 +0000476 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000477 PyMethod_Fini();
478 PyFrame_Fini();
479 PyCFunction_Fini();
480 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000481 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000482 PySet_Fini();
Christian Heimes72b710a2008-05-26 13:28:38 +0000483 PyBytes_Fini();
Christian Heimes9c4756e2008-05-26 13:22:05 +0000484 PyByteArray_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000485 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000486 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000487 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000488
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000489 /* Cleanup Unicode implementation */
490 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000491
Christian Heimesc8967002007-11-30 10:18:26 +0000492 /* reset file system default encoding */
493 if (!Py_HasFileSystemDefaultEncoding) {
494 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000495 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000496 }
497
Guido van Rossumcc283f51997-08-05 02:22:03 +0000498 /* XXX Still allocated:
499 - various static ad-hoc pointers to interned strings
500 - int and float free list blocks
501 - whatever various modules and libraries allocate
502 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000503
504 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000505
Tim Peters269b2a62003-04-17 19:52:29 +0000506#ifdef Py_TRACE_REFS
507 /* Display addresses (& refcnts) of all objects still alive.
508 * An address can be used to find the repr of the object, printed
509 * above by _Py_PrintReferences.
510 */
511 if (Py_GETENV("PYTHONDUMPREFS"))
512 _Py_PrintReferenceAddresses(stderr);
513#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000514#ifdef PYMALLOC_DEBUG
515 if (Py_GETENV("PYTHONMALLOCSTATS"))
516 _PyObject_DebugMallocStats();
517#endif
518
Guido van Rossumcc283f51997-08-05 02:22:03 +0000519 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000520}
521
522/* Create and initialize a new interpreter and thread, and return the
523 new thread. This requires that Py_Initialize() has been called
524 first.
525
526 Unsuccessful initialization yields a NULL pointer. Note that *no*
527 exception information is available even in this case -- the
528 exception information is held in the thread, and there is no
529 thread.
530
531 Locking: as above.
532
533*/
534
535PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000536Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000537{
538 PyInterpreterState *interp;
539 PyThreadState *tstate, *save_tstate;
540 PyObject *bimod, *sysmod;
541
542 if (!initialized)
543 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
544
545 interp = PyInterpreterState_New();
546 if (interp == NULL)
547 return NULL;
548
549 tstate = PyThreadState_New(interp);
550 if (tstate == NULL) {
551 PyInterpreterState_Delete(interp);
552 return NULL;
553 }
554
555 save_tstate = PyThreadState_Swap(tstate);
556
557 /* XXX The following is lax in error checking */
558
559 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000560 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561
Georg Brandl1a3284e2007-12-02 09:40:06 +0000562 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000563 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000564 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000565 if (interp->builtins == NULL)
566 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000567 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000568 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000569
570 /* initialize builtin exceptions */
571 _PyExc_Init();
572
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573 sysmod = _PyImport_FindExtension("sys", "sys");
574 if (bimod != NULL && sysmod != NULL) {
Christian Heimes6a27efa2008-10-30 21:48:26 +0000575 PyObject *pstderr;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000577 if (interp->sysdict == NULL)
578 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579 Py_INCREF(interp->sysdict);
580 PySys_SetPath(Py_GetPath());
581 PyDict_SetItemString(interp->sysdict, "modules",
582 interp->modules);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000583 /* Set up a preliminary stderr printer until we have enough
584 infrastructure for the io module in place. */
585 pstderr = PyFile_NewStdPrinter(fileno(stderr));
586 if (pstderr == NULL)
587 Py_FatalError("Py_Initialize: can't set preliminary stderr");
588 PySys_SetObject("stderr", pstderr);
589 PySys_SetObject("__stderr__", pstderr);
590
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000591 _PyImportHooks_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000592 if (initstdio() < 0)
593 Py_FatalError(
594 "Py_Initialize: can't initialize sys standard streams");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000595 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000596 if (!Py_NoSiteFlag)
597 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000598 }
599
600 if (!PyErr_Occurred())
601 return tstate;
602
Thomas Wouters89f507f2006-12-13 04:49:30 +0000603handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000604 /* Oops, it didn't work. Undo it all. */
605
606 PyErr_Print();
607 PyThreadState_Clear(tstate);
608 PyThreadState_Swap(save_tstate);
609 PyThreadState_Delete(tstate);
610 PyInterpreterState_Delete(interp);
611
612 return NULL;
613}
614
615/* Delete an interpreter and its last thread. This requires that the
616 given thread state is current, that the thread has no remaining
617 frames, and that it is its interpreter's only remaining thread.
618 It is a fatal error to violate these constraints.
619
620 (Py_Finalize() doesn't have these constraints -- it zaps
621 everything, regardless.)
622
623 Locking: as above.
624
625*/
626
627void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000628Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629{
630 PyInterpreterState *interp = tstate->interp;
631
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000632 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633 Py_FatalError("Py_EndInterpreter: thread is not current");
634 if (tstate->frame != NULL)
635 Py_FatalError("Py_EndInterpreter: thread still has a frame");
636 if (tstate != interp->tstate_head || tstate->next != NULL)
637 Py_FatalError("Py_EndInterpreter: not the last thread");
638
639 PyImport_Cleanup();
640 PyInterpreterState_Clear(interp);
641 PyThreadState_Swap(NULL);
642 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000643}
644
Martin v. Löwis790465f2008-04-05 20:41:37 +0000645static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000646
647void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000648Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000649{
650 if (pn && *pn)
651 progname = pn;
652}
653
Martin v. Löwis790465f2008-04-05 20:41:37 +0000654wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000655Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000656{
657 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000658}
659
Martin v. Löwis790465f2008-04-05 20:41:37 +0000660static wchar_t *default_home = NULL;
661static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000662
663void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000664Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000665{
666 default_home = home;
667}
668
Martin v. Löwis790465f2008-04-05 20:41:37 +0000669wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000670Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000671{
Martin v. Löwis790465f2008-04-05 20:41:37 +0000672 wchar_t *home = default_home;
673 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
674 char* chome = Py_GETENV("PYTHONHOME");
675 if (chome) {
676 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
677 if (r != (size_t)-1 && r <= PATH_MAX)
678 home = env_home;
679 }
680
681 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000682 return home;
683}
684
Guido van Rossum6135a871995-01-09 17:53:26 +0000685/* Create __main__ module */
686
687static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000688initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000689{
Guido van Rossum82598051997-03-05 00:20:32 +0000690 PyObject *m, *d;
691 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000692 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000693 Py_FatalError("can't create __main__ module");
694 d = PyModule_GetDict(m);
695 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000696 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000697 if (bimod == NULL ||
698 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000699 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000700 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000701 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000702}
703
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000704/* Import the site module (not into __main__ though) */
705
706static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000707initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000708{
709 PyObject *m, *f;
710 m = PyImport_ImportModule("site");
711 if (m == NULL) {
712 f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +0000713 if (f == NULL || f == Py_None)
714 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000715 if (Py_VerboseFlag) {
716 PyFile_WriteString(
717 "'import site' failed; traceback:\n", f);
718 PyErr_Print();
719 }
720 else {
721 PyFile_WriteString(
722 "'import site' failed; use -v for traceback\n", f);
723 PyErr_Clear();
724 }
725 }
726 else {
727 Py_DECREF(m);
728 }
729}
730
Georg Brandl1a3284e2007-12-02 09:40:06 +0000731/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000732static int
733initstdio(void)
734{
735 PyObject *iomod = NULL, *wrapper;
736 PyObject *bimod = NULL;
737 PyObject *m;
738 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000739 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000740 PyObject * encoding_attr;
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +0000741 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000742
743 /* Hack to avoid a nasty recursion issue when Python is invoked
744 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
745 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
746 goto error;
747 }
748 Py_DECREF(m);
749
750 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
751 goto error;
752 }
753 Py_DECREF(m);
754
Georg Brandl1a3284e2007-12-02 09:40:06 +0000755 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000756 goto error;
757 }
758
759 if (!(iomod = PyImport_ImportModule("io"))) {
760 goto error;
761 }
762 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
763 goto error;
764 }
765
Georg Brandl1a3284e2007-12-02 09:40:06 +0000766 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000767 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
768 goto error;
769 }
770
Martin v. Löwis0f599892008-06-02 11:13:03 +0000771 encoding = Py_GETENV("PYTHONIOENCODING");
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000772 errors = NULL;
Martin v. Löwis0f599892008-06-02 11:13:03 +0000773 if (encoding) {
774 encoding = strdup(encoding);
775 errors = strchr(encoding, ':');
776 if (errors) {
777 *errors = '\0';
778 errors++;
779 }
780 }
781
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000782 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000783 fd = fileno(stdin);
784 /* Under some conditions stdin, stdout and stderr may not be connected
785 * and fileno() may point to an invalid file descriptor. For example
786 * GUI apps don't have valid standard streams by default.
787 */
788 if (fd < 0) {
789#ifdef MS_WINDOWS
790 std = Py_None;
791 Py_INCREF(std);
792#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000793 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000794#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000795 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000796 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000797 if (!(std = PyFile_FromFd(fd, "<stdin>", "r", -1, encoding,
798 errors, "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000799 goto error;
800 }
801 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000802 PySys_SetObject("__stdin__", std);
803 PySys_SetObject("stdin", std);
804 Py_DECREF(std);
805
806 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000807 fd = fileno(stdout);
808 if (fd < 0) {
809#ifdef MS_WINDOWS
810 std = Py_None;
811 Py_INCREF(std);
812#else
813 goto error;
814#endif
815 }
816 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000817 if (!(std = PyFile_FromFd(fd, "<stdout>", "w", -1, encoding,
818 errors, "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000819 goto error;
820 }
821 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000822 PySys_SetObject("__stdout__", std);
823 PySys_SetObject("stdout", std);
824 Py_DECREF(std);
825
Guido van Rossum98297ee2007-11-06 21:34:58 +0000826#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000827 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000828 fd = fileno(stderr);
829 if (fd < 0) {
830#ifdef MS_WINDOWS
831 std = Py_None;
832 Py_INCREF(std);
833#else
834 goto error;
835#endif
836 }
837 else {
Martin v. Löwis0f599892008-06-02 11:13:03 +0000838 if (!(std = PyFile_FromFd(fd, "<stderr>", "w", -1, encoding,
Georg Brandl559e5d72008-06-11 18:37:52 +0000839 "backslashreplace", "\n", 0))) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000840 goto error;
841 }
842 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000843
844 /* Same as hack above, pre-import stderr's codec to avoid recursion
845 when import.c tries to write to stderr in verbose mode. */
846 encoding_attr = PyObject_GetAttrString(std, "encoding");
847 if (encoding_attr != NULL) {
848 const char * encoding;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000849 encoding = _PyUnicode_AsString(encoding_attr);
Trent Nelson39e307e2008-03-19 06:45:48 +0000850 if (encoding != NULL) {
851 _PyCodec_Lookup(encoding);
852 }
853 }
854 PyErr_Clear(); /* Not a fatal error if codec isn't available */
855
Christian Heimesdb233082007-11-13 02:34:21 +0000856 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000857 PySys_SetObject("stderr", std);
858 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000859#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000860
Christian Heimes58cb1b82007-11-13 02:19:40 +0000861 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000862 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000863 status = -1;
864 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000865
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000866 if (encoding)
867 free(encoding);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000868 Py_XDECREF(bimod);
869 Py_XDECREF(iomod);
870 return status;
871}
872
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000873/* Parse input from a file and execute it */
874
875int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000876PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000877 PyCompilerFlags *flags)
878{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000879 if (filename == NULL)
880 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000881 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000882 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000883 if (closeit)
884 fclose(fp);
885 return err;
886 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000887 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000888 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000889}
890
891int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000892PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000893{
Guido van Rossum82598051997-03-05 00:20:32 +0000894 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000895 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000896 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000897
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000898 if (flags == NULL) {
899 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000900 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000901 }
Guido van Rossum82598051997-03-05 00:20:32 +0000902 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000903 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000904 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000905 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000906 }
Guido van Rossum82598051997-03-05 00:20:32 +0000907 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000908 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000909 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000910 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000911 }
912 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000913 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000914 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000915 if (ret == E_EOF)
916 return 0;
917 /*
918 if (ret == E_NOMEM)
919 return -1;
920 */
921 }
922}
923
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000924/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000925#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000926 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Guido van Rossum45aecf42006-03-15 04:58:47 +0000927 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000928
Thomas Wouters89f507f2006-12-13 04:49:30 +0000929#if 0
930/* Keep an example of flags with future keyword support. */
931#define PARSER_FLAGS(flags) \
932 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
933 PyPARSE_DONT_IMPLY_DEDENT : 0) \
934 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
935 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
936#endif
937
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000938int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000939PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000940{
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000941 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000942 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +0000943 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000944 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000945 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000946
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000947 if (fp == stdin) {
948 /* Fetch encoding from sys.stdin */
949 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +0000950 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000951 return -1;
952 oenc = PyObject_GetAttrString(v, "encoding");
953 if (!oenc)
954 return -1;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000955 enc = _PyUnicode_AsString(oenc);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000956 }
Guido van Rossum82598051997-03-05 00:20:32 +0000957 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000958 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000959 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000960 if (v == NULL)
961 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000962 else if (PyUnicode_Check(v))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000963 ps1 = _PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000964 }
Guido van Rossum82598051997-03-05 00:20:32 +0000965 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000966 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000967 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000968 if (w == NULL)
969 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000970 else if (PyUnicode_Check(w))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000971 ps2 = _PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000972 }
Neal Norwitz9589ee22006-03-04 19:01:22 +0000973 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000974 if (arena == NULL) {
975 Py_XDECREF(v);
976 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000977 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000978 return -1;
979 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000980 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000982 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +0000983 Py_XDECREF(v);
984 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000985 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000987 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000988 if (errcode == E_EOF) {
989 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000990 return E_EOF;
991 }
Guido van Rossum82598051997-03-05 00:20:32 +0000992 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000993 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000994 }
Guido van Rossum82598051997-03-05 00:20:32 +0000995 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000996 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000997 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000998 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000999 }
Guido van Rossum82598051997-03-05 00:20:32 +00001000 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001001 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001002 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001003 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001004 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001005 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001006 return -1;
1007 }
Guido van Rossum82598051997-03-05 00:20:32 +00001008 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001009 return 0;
1010}
1011
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001012/* Check whether a file maybe a pyc file: Look at the extension,
1013 the file type, and, if we may close it, at the first few bytes. */
1014
1015static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001016maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001017{
1018 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1019 return 1;
1020
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001021 /* Only look into the file if we are allowed to close it, since
1022 it then should also be seekable. */
1023 if (closeit) {
1024 /* Read only two bytes of the magic. If the file was opened in
1025 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1026 be read as they are on disk. */
1027 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1028 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001029 /* Mess: In case of -x, the stream is NOT at its start now,
1030 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001031 which makes the current stream position formally undefined,
1032 and a x-platform nightmare.
1033 Unfortunately, we have no direct way to know whether -x
1034 was specified. So we use a terrible hack: if the current
1035 stream position is not 0, we assume -x was specified, and
1036 give up. Bug 132850 on SourceForge spells out the
1037 hopelessness of trying anything else (fseek and ftell
1038 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001039 */
Tim Peters3e876562001-02-11 04:35:39 +00001040 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001041 if (ftell(fp) == 0) {
1042 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001043 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001044 ispyc = 1;
1045 rewind(fp);
1046 }
Tim Peters3e876562001-02-11 04:35:39 +00001047 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001048 }
1049 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001050}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001051
Guido van Rossum0df002c2000-08-27 19:21:52 +00001052int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001053PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001054 PyCompilerFlags *flags)
1055{
Guido van Rossum82598051997-03-05 00:20:32 +00001056 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001057 const char *ext;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001058 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001059
Guido van Rossum82598051997-03-05 00:20:32 +00001060 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001061 if (m == NULL)
1062 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001063 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001064 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001065 PyObject *f;
1066 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001067 if (f == NULL)
1068 return -1;
1069 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1070 Py_DECREF(f);
1071 return -1;
1072 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001073 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001074 Py_DECREF(f);
1075 }
Guido van Rossumfdef2711994-09-14 13:31:04 +00001076 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001077 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001078 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001079 if (closeit)
1080 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001081 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001082 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001083 ret = -1;
1084 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001085 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001086 /* Turn on optimization if a .pyo file is given */
1087 if (strcmp(ext, ".pyo") == 0)
1088 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001089 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001090 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001091 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001092 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001093 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001094 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001095 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001096 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001097 ret = -1;
1098 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001099 }
Guido van Rossum82598051997-03-05 00:20:32 +00001100 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001101 ret = 0;
1102 done:
1103 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1104 PyErr_Clear();
1105 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001106}
1107
1108int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001109PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001110{
Guido van Rossum82598051997-03-05 00:20:32 +00001111 PyObject *m, *d, *v;
1112 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001113 if (m == NULL)
1114 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001115 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001116 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001117 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001118 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001119 return -1;
1120 }
Guido van Rossum82598051997-03-05 00:20:32 +00001121 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001122 return 0;
1123}
1124
Barry Warsaw035574d1997-08-29 22:07:17 +00001125static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001126parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1127 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001128{
1129 long hold;
1130 PyObject *v;
1131
1132 /* old style errors */
1133 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001134 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001135 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001136
1137 /* new style errors. `err' is an instance */
1138
1139 if (! (v = PyObject_GetAttrString(err, "msg")))
1140 goto finally;
1141 *message = v;
1142
1143 if (!(v = PyObject_GetAttrString(err, "filename")))
1144 goto finally;
1145 if (v == Py_None)
1146 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001147 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001148 goto finally;
1149
1150 Py_DECREF(v);
1151 if (!(v = PyObject_GetAttrString(err, "lineno")))
1152 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001153 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001154 Py_DECREF(v);
1155 v = NULL;
1156 if (hold < 0 && PyErr_Occurred())
1157 goto finally;
1158 *lineno = (int)hold;
1159
1160 if (!(v = PyObject_GetAttrString(err, "offset")))
1161 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001162 if (v == Py_None) {
1163 *offset = -1;
1164 Py_DECREF(v);
1165 v = NULL;
1166 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001167 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001168 Py_DECREF(v);
1169 v = NULL;
1170 if (hold < 0 && PyErr_Occurred())
1171 goto finally;
1172 *offset = (int)hold;
1173 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001174
1175 if (!(v = PyObject_GetAttrString(err, "text")))
1176 goto finally;
1177 if (v == Py_None)
1178 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001179 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001180 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001181 goto finally;
1182 Py_DECREF(v);
1183 return 1;
1184
1185finally:
1186 Py_XDECREF(v);
1187 return 0;
1188}
1189
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001190void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001191PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001192{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001193 PyErr_PrintEx(1);
1194}
1195
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001196static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001197print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001198{
1199 char *nl;
1200 if (offset >= 0) {
1201 if (offset > 0 && offset == (int)strlen(text))
1202 offset--;
1203 for (;;) {
1204 nl = strchr(text, '\n');
1205 if (nl == NULL || nl-text >= offset)
1206 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001207 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001208 text = nl+1;
1209 }
1210 while (*text == ' ' || *text == '\t') {
1211 text++;
1212 offset--;
1213 }
1214 }
1215 PyFile_WriteString(" ", f);
1216 PyFile_WriteString(text, f);
1217 if (*text == '\0' || text[strlen(text)-1] != '\n')
1218 PyFile_WriteString("\n", f);
1219 if (offset == -1)
1220 return;
1221 PyFile_WriteString(" ", f);
1222 offset--;
1223 while (offset > 0) {
1224 PyFile_WriteString(" ", f);
1225 offset--;
1226 }
1227 PyFile_WriteString("^\n", f);
1228}
1229
Guido van Rossum66e8e862001-03-23 17:54:43 +00001230static void
1231handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001232{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001233 PyObject *exception, *value, *tb;
1234 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001235
Guido van Rossumd8faa362007-04-27 19:54:29 +00001236 if (Py_InspectFlag)
1237 /* Don't exit if -i flag was given. This flag is set to 0
1238 * when entering interactive mode for inspecting. */
1239 return;
1240
Guido van Rossum66e8e862001-03-23 17:54:43 +00001241 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001242 fflush(stdout);
1243 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001244 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001245 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001246 /* The error code should be in the `code' attribute. */
1247 PyObject *code = PyObject_GetAttrString(value, "code");
1248 if (code) {
1249 Py_DECREF(value);
1250 value = code;
1251 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001252 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001253 }
1254 /* If we failed to dig out the 'code' attribute,
1255 just let the else clause below print the error. */
1256 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001257 if (PyLong_Check(value))
1258 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001259 else {
1260 PyObject_Print(value, stderr, Py_PRINT_RAW);
1261 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001262 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001263 }
Tim Peterscf615b52003-04-19 18:47:02 +00001264 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001265 /* Restore and clear the exception info, in order to properly decref
1266 * the exception, value, and traceback. If we just exit instead,
1267 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1268 * some finalizers from running.
1269 */
Tim Peterscf615b52003-04-19 18:47:02 +00001270 PyErr_Restore(exception, value, tb);
1271 PyErr_Clear();
1272 Py_Exit(exitcode);
1273 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001274}
1275
1276void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001277PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001278{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001279 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001280
1281 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1282 handle_system_exit();
1283 }
Guido van Rossum82598051997-03-05 00:20:32 +00001284 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001285 if (exception == NULL)
1286 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001287 PyErr_NormalizeException(&exception, &v, &tb);
Antoine Pitroue2dffc02008-08-26 22:02:58 +00001288 if (tb == NULL) {
1289 tb = Py_None;
1290 Py_INCREF(tb);
1291 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001292 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001293 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001294 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001295 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001296 if (set_sys_last_vars) {
1297 PySys_SetObject("last_type", exception);
1298 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001299 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001300 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001301 hook = PySys_GetObject("excepthook");
1302 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001303 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001304 PyObject *result = PyEval_CallObject(hook, args);
1305 if (result == NULL) {
1306 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001307 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1308 handle_system_exit();
1309 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001310 PyErr_Fetch(&exception2, &v2, &tb2);
1311 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001312 /* It should not be possible for exception2 or v2
1313 to be NULL. However PyErr_Display() can't
1314 tolerate NULLs, so just be safe. */
1315 if (exception2 == NULL) {
1316 exception2 = Py_None;
1317 Py_INCREF(exception2);
1318 }
1319 if (v2 == NULL) {
1320 v2 = Py_None;
1321 Py_INCREF(v2);
1322 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001323 fflush(stdout);
1324 PySys_WriteStderr("Error in sys.excepthook:\n");
1325 PyErr_Display(exception2, v2, tb2);
1326 PySys_WriteStderr("\nOriginal exception was:\n");
1327 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001328 Py_DECREF(exception2);
1329 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001330 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001331 }
1332 Py_XDECREF(result);
1333 Py_XDECREF(args);
1334 } else {
1335 PySys_WriteStderr("sys.excepthook is missing\n");
1336 PyErr_Display(exception, v, tb);
1337 }
1338 Py_XDECREF(exception);
1339 Py_XDECREF(v);
1340 Py_XDECREF(tb);
1341}
1342
Benjamin Petersone6528212008-07-15 15:32:09 +00001343static void
1344print_exception(PyObject *f, PyObject *value)
1345{
1346 int err = 0;
1347 PyObject *type, *tb;
1348
Benjamin Peterson26582602008-08-23 20:08:07 +00001349 if (!PyExceptionInstance_Check(value)) {
1350 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1351 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1352 PyFile_WriteString(" found\n", f);
1353 return;
1354 }
1355
Benjamin Petersone6528212008-07-15 15:32:09 +00001356 Py_INCREF(value);
1357 fflush(stdout);
1358 type = (PyObject *) Py_TYPE(value);
1359 tb = PyException_GetTraceback(value);
1360 if (tb && tb != Py_None)
1361 err = PyTraceBack_Print(tb, f);
1362 if (err == 0 &&
1363 PyObject_HasAttrString(value, "print_file_and_line"))
1364 {
1365 PyObject *message;
1366 const char *filename, *text;
1367 int lineno, offset;
1368 if (!parse_syntax_error(value, &message, &filename,
1369 &lineno, &offset, &text))
1370 PyErr_Clear();
1371 else {
1372 char buf[10];
1373 PyFile_WriteString(" File \"", f);
1374 if (filename == NULL)
1375 PyFile_WriteString("<string>", f);
1376 else
1377 PyFile_WriteString(filename, f);
1378 PyFile_WriteString("\", line ", f);
1379 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1380 PyFile_WriteString(buf, f);
1381 PyFile_WriteString("\n", f);
1382 if (text != NULL)
1383 print_error_text(f, offset, text);
1384 Py_DECREF(value);
1385 value = message;
1386 /* Can't be bothered to check all those
1387 PyFile_WriteString() calls */
1388 if (PyErr_Occurred())
1389 err = -1;
1390 }
1391 }
1392 if (err) {
1393 /* Don't do anything else */
1394 }
1395 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001396 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001397 char* className;
1398 assert(PyExceptionClass_Check(type));
1399 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001400 if (className != NULL) {
1401 char *dot = strrchr(className, '.');
1402 if (dot != NULL)
1403 className = dot+1;
1404 }
1405
1406 moduleName = PyObject_GetAttrString(type, "__module__");
1407 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1408 {
1409 Py_DECREF(moduleName);
1410 err = PyFile_WriteString("<unknown>", f);
1411 }
1412 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001413 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001414 if (modstr && strcmp(modstr, "builtins"))
1415 {
1416 err = PyFile_WriteString(modstr, f);
1417 err += PyFile_WriteString(".", f);
1418 }
1419 Py_DECREF(moduleName);
1420 }
1421 if (err == 0) {
1422 if (className == NULL)
1423 err = PyFile_WriteString("<unknown>", f);
1424 else
1425 err = PyFile_WriteString(className, f);
1426 }
1427 }
1428 if (err == 0 && (value != Py_None)) {
1429 PyObject *s = PyObject_Str(value);
1430 /* only print colon if the str() of the
1431 object is not the empty string
1432 */
1433 if (s == NULL)
1434 err = -1;
1435 else if (!PyUnicode_Check(s) ||
1436 PyUnicode_GetSize(s) != 0)
1437 err = PyFile_WriteString(": ", f);
1438 if (err == 0)
1439 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1440 Py_XDECREF(s);
1441 }
1442 /* try to write a newline in any case */
1443 err += PyFile_WriteString("\n", f);
1444 Py_XDECREF(tb);
1445 Py_DECREF(value);
1446 /* If an error happened here, don't show it.
1447 XXX This is wrong, but too many callers rely on this behavior. */
1448 if (err != 0)
1449 PyErr_Clear();
1450}
1451
1452static const char *cause_message =
1453 "\nThe above exception was the direct cause "
1454 "of the following exception:\n\n";
1455
1456static const char *context_message =
1457 "\nDuring handling of the above exception, "
1458 "another exception occurred:\n\n";
1459
1460static void
1461print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1462{
1463 int err = 0, res;
1464 PyObject *cause, *context;
1465
1466 if (seen != NULL) {
1467 /* Exception chaining */
1468 if (PySet_Add(seen, value) == -1)
1469 PyErr_Clear();
1470 else if (PyExceptionInstance_Check(value)) {
1471 cause = PyException_GetCause(value);
1472 context = PyException_GetContext(value);
1473 if (cause) {
1474 res = PySet_Contains(seen, cause);
1475 if (res == -1)
1476 PyErr_Clear();
1477 if (res == 0) {
1478 print_exception_recursive(
1479 f, cause, seen);
1480 err |= PyFile_WriteString(
1481 cause_message, f);
1482 }
1483 }
1484 if (context) {
1485 res = PySet_Contains(seen, context);
1486 if (res == -1)
1487 PyErr_Clear();
1488 if (res == 0) {
1489 print_exception_recursive(
1490 f, context, seen);
1491 err |= PyFile_WriteString(
1492 context_message, f);
1493 }
1494 }
1495 Py_XDECREF(context);
1496 Py_XDECREF(cause);
1497 }
1498 }
1499 print_exception(f, value);
1500 if (err != 0)
1501 PyErr_Clear();
1502}
1503
Thomas Wouters477c8d52006-05-27 19:21:47 +00001504void
1505PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001506{
Benjamin Petersone6528212008-07-15 15:32:09 +00001507 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001508 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001509 if (f == Py_None) {
1510 /* pass */
1511 }
1512 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001513 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001514 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001515 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001516 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001517 /* We choose to ignore seen being possibly NULL, and report
1518 at least the main exception (it could be a MemoryError).
1519 */
1520 seen = PySet_New(NULL);
1521 if (seen == NULL)
1522 PyErr_Clear();
1523 print_exception_recursive(f, value, seen);
1524 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001525 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001526}
1527
Guido van Rossum82598051997-03-05 00:20:32 +00001528PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001529PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001530 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001531{
Neal Norwitze92fba02006-03-04 18:52:26 +00001532 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001533 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001534 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001535 if (arena == NULL)
1536 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001537
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001538 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001539 if (mod != NULL)
1540 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001541 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001542 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001543}
1544
1545PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001546PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001547 PyObject *locals, int closeit, PyCompilerFlags *flags)
1548{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001549 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001550 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001551 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001552 if (arena == NULL)
1553 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001554
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001555 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001556 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001557 if (closeit)
1558 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001559 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001560 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001561 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001562 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001563 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001564 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001565 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001566}
1567
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001568static void
1569flush_io(void)
1570{
1571 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001572 PyObject *type, *value, *traceback;
1573
1574 /* Save the current exception */
1575 PyErr_Fetch(&type, &value, &traceback);
1576
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001577 f = PySys_GetObject("stderr");
1578 if (f != NULL) {
1579 r = PyObject_CallMethod(f, "flush", "");
1580 if (r)
1581 Py_DECREF(r);
1582 else
1583 PyErr_Clear();
1584 }
1585 f = PySys_GetObject("stdout");
1586 if (f != NULL) {
1587 r = PyObject_CallMethod(f, "flush", "");
1588 if (r)
1589 Py_DECREF(r);
1590 else
1591 PyErr_Clear();
1592 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001593
1594 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001595}
1596
Guido van Rossum82598051997-03-05 00:20:32 +00001597static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001598run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001599 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001600{
Guido van Rossum82598051997-03-05 00:20:32 +00001601 PyCodeObject *co;
1602 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001603 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001604 if (co == NULL)
1605 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001606 v = PyEval_EvalCode(co, globals, locals);
1607 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001608 return v;
1609}
1610
Guido van Rossum82598051997-03-05 00:20:32 +00001611static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001612run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001613 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001614{
Guido van Rossum82598051997-03-05 00:20:32 +00001615 PyCodeObject *co;
1616 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001617 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001618 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001619
Guido van Rossum82598051997-03-05 00:20:32 +00001620 magic = PyMarshal_ReadLongFromFile(fp);
1621 if (magic != PyImport_GetMagicNumber()) {
1622 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001623 "Bad magic number in .pyc file");
1624 return NULL;
1625 }
Guido van Rossum82598051997-03-05 00:20:32 +00001626 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001627 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001628 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001629 if (v == NULL || !PyCode_Check(v)) {
1630 Py_XDECREF(v);
1631 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001632 "Bad code object in .pyc file");
1633 return NULL;
1634 }
Guido van Rossum82598051997-03-05 00:20:32 +00001635 co = (PyCodeObject *)v;
1636 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001637 if (v && flags)
1638 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001639 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001640 return v;
1641}
1642
Guido van Rossum82598051997-03-05 00:20:32 +00001643PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001644Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001645 PyCompilerFlags *flags)
1646{
Guido van Rossum82598051997-03-05 00:20:32 +00001647 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001648 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001649 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001650 if (arena == NULL)
1651 return NULL;
1652
1653 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001654 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001655 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001656 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001657 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001658 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001659 PyObject *result = PyAST_mod2obj(mod);
1660 PyArena_Free(arena);
1661 return result;
1662 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001663 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001664 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001665 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001666}
1667
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001668struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001669Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001670{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001671 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001672 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001673 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001674 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001675 if (arena == NULL)
1676 return NULL;
1677
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001678 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001679 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001680 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001681 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001682 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001683 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001684 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001685 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001686 return st;
1687}
1688
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001689/* Preferred access to parser is through AST. */
1690mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001691PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001692 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001693{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001694 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001695 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001696 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001697 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001698
1699 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001700 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001701 &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001702 if (flags == NULL) {
1703 localflags.cf_flags = 0;
1704 flags = &localflags;
1705 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001706 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001707 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001708 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001709 PyNode_Free(n);
1710 return mod;
1711 }
1712 else {
1713 err_input(&err);
1714 return NULL;
1715 }
1716}
1717
1718mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001719PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1720 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001721 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001722 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001723{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001724 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001725 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001726 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001727 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001728
Christian Heimes4d6ec852008-03-26 22:34:47 +00001729 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001730 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001731 start, ps1, ps2, &err, &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001732 if (flags == NULL) {
1733 localflags.cf_flags = 0;
1734 flags = &localflags;
1735 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001736 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001737 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001738 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001739 PyNode_Free(n);
1740 return mod;
1741 }
1742 else {
1743 err_input(&err);
1744 if (errcode)
1745 *errcode = err.error;
1746 return NULL;
1747 }
1748}
1749
Guido van Rossuma110aa61994-08-29 12:50:44 +00001750/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001751
Guido van Rossuma110aa61994-08-29 12:50:44 +00001752node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001753PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001754{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001755 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001756 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1757 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001758 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001759 if (n == NULL)
1760 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001761
Guido van Rossuma110aa61994-08-29 12:50:44 +00001762 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001763}
1764
Guido van Rossuma110aa61994-08-29 12:50:44 +00001765/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001766
Guido van Rossuma110aa61994-08-29 12:50:44 +00001767node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001768PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001769{
Tim Petersfe2127d2001-07-16 05:37:24 +00001770 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001771 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1772 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001773 if (n == NULL)
1774 err_input(&err);
1775 return n;
1776}
1777
1778node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001779PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001780 int start, int flags)
1781{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001782 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001783 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1784 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001785 if (n == NULL)
1786 err_input(&err);
1787 return n;
1788}
1789
1790node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001791PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001792{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001793 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001794}
1795
Guido van Rossum66ebd912003-04-17 16:02:26 +00001796/* May want to move a more generalized form of this to parsetok.c or
1797 even parser modules. */
1798
1799void
1800PyParser_SetError(perrdetail *err)
1801{
1802 err_input(err);
1803}
1804
Guido van Rossuma110aa61994-08-29 12:50:44 +00001805/* Set the error appropriate to the given input error code (see errcode.h) */
1806
1807static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001808err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001809{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001810 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001811 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001812 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001813 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001814 switch (err->error) {
1815 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001816 errtype = PyExc_IndentationError;
1817 if (err->expected == INDENT)
1818 msg = "expected an indented block";
1819 else if (err->token == INDENT)
1820 msg = "unexpected indent";
1821 else if (err->token == DEDENT)
1822 msg = "unexpected unindent";
1823 else {
1824 errtype = PyExc_SyntaxError;
1825 msg = "invalid syntax";
1826 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001827 break;
1828 case E_TOKEN:
1829 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001830 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001831 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001832 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001833 break;
1834 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001835 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001836 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001837 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001838 if (!PyErr_Occurred())
1839 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001840 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001841 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001842 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001843 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001844 case E_EOF:
1845 msg = "unexpected EOF while parsing";
1846 break;
Fred Drake85f36392000-07-11 17:53:00 +00001847 case E_TABSPACE:
1848 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001849 msg = "inconsistent use of tabs and spaces in indentation";
1850 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001851 case E_OVERFLOW:
1852 msg = "expression too long";
1853 break;
Fred Drake85f36392000-07-11 17:53:00 +00001854 case E_DEDENT:
1855 errtype = PyExc_IndentationError;
1856 msg = "unindent does not match any outer indentation level";
1857 break;
1858 case E_TOODEEP:
1859 errtype = PyExc_IndentationError;
1860 msg = "too many levels of indentation";
1861 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001862 case E_DECODE: {
1863 PyObject *type, *value, *tb;
1864 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001865 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001866 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001867 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001868 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001869 }
1870 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001871 if (msg == NULL)
1872 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001873 Py_XDECREF(type);
1874 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001875 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001876 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001877 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001878 case E_LINECONT:
1879 msg = "unexpected character after line continuation character";
1880 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001881
1882 case E_IDENTIFIER:
1883 msg = "invalid character in identifier";
1884 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001885 default:
1886 fprintf(stderr, "error=%d\n", err->error);
1887 msg = "unknown parsing error";
1888 break;
1889 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001890 /* err->text may not be UTF-8 in case of decoding errors.
1891 Explicitly convert to an object. */
1892 if (!err->text) {
1893 errtext = Py_None;
1894 Py_INCREF(Py_None);
1895 } else {
1896 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1897 "replace");
1898 }
1899 v = Py_BuildValue("(ziiN)", err->filename,
1900 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001901 w = NULL;
1902 if (v != NULL)
1903 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001904 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001905 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001906 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001907 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001908cleanup:
1909 if (err->text != NULL) {
1910 PyObject_FREE(err->text);
1911 err->text = NULL;
1912 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001913}
1914
1915/* Print fatal error message and abort */
1916
1917void
Tim Peters7c321a82002-07-09 02:57:01 +00001918Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001919{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001920 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001921 if (PyErr_Occurred()) {
1922 PyErr_Print();
1923 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001924#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +00001925 {
1926 size_t len = strlen(msg);
1927 WCHAR* buffer;
1928 size_t i;
1929
1930 /* Convert the message to wchar_t. This uses a simple one-to-one
1931 conversion, assuming that the this error message actually uses ASCII
1932 only. If this ceases to be true, we will have to convert. */
1933 buffer = alloca( (len+1) * (sizeof *buffer));
1934 for( i=0; i<=len; ++i)
1935 buffer[i] = msg[i];
1936 OutputDebugStringW(L"Fatal Python error: ");
1937 OutputDebugStringW(buffer);
1938 OutputDebugStringW(L"\n");
1939 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00001940#ifdef _DEBUG
1941 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001942#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001943#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001944 abort();
1945}
1946
1947/* Clean up and exit */
1948
Guido van Rossuma110aa61994-08-29 12:50:44 +00001949#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001950#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001951#endif
1952
Collin Winter670e6922007-03-21 02:57:17 +00001953static void (*pyexitfunc)(void) = NULL;
1954/* For the atexit module. */
1955void _Py_PyAtExit(void (*func)(void))
1956{
1957 pyexitfunc = func;
1958}
1959
1960static void
1961call_py_exitfuncs(void)
1962{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001963 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00001964 return;
1965
1966 (*pyexitfunc)();
1967 PyErr_Clear();
1968}
1969
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001970#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001971static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001972static int nexitfuncs = 0;
1973
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001974int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001975{
1976 if (nexitfuncs >= NEXITFUNCS)
1977 return -1;
1978 exitfuncs[nexitfuncs++] = func;
1979 return 0;
1980}
1981
Guido van Rossumcc283f51997-08-05 02:22:03 +00001982static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001983call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001984{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001985 while (nexitfuncs > 0)
1986 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001987
1988 fflush(stdout);
1989 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001990}
1991
1992void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001993Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001994{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001995 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001996
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001997 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001998}
1999
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002000static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002001initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002002{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002003#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002004 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002005#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002006#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002007 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002008#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002009#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002010 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002011#endif
Guido van Rossum82598051997-03-05 00:20:32 +00002012 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002013}
2014
Guido van Rossum7433b121997-02-14 19:45:36 +00002015
2016/*
2017 * The file descriptor fd is considered ``interactive'' if either
2018 * a) isatty(fd) is TRUE, or
2019 * b) the -i flag was given, and the filename associated with
2020 * the descriptor is NULL or "<stdin>" or "???".
2021 */
2022int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002023Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002024{
2025 if (isatty((int)fileno(fp)))
2026 return 1;
2027 if (!Py_InteractiveFlag)
2028 return 0;
2029 return (filename == NULL) ||
2030 (strcmp(filename, "<stdin>") == 0) ||
2031 (strcmp(filename, "???") == 0);
2032}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002033
2034
Tim Petersd08e3822003-04-17 15:24:21 +00002035#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002036#if defined(WIN32) && defined(_MSC_VER)
2037
2038/* Stack checking for Microsoft C */
2039
2040#include <malloc.h>
2041#include <excpt.h>
2042
Fred Drakee8de31c2000-08-31 05:38:39 +00002043/*
2044 * Return non-zero when we run out of memory on the stack; zero otherwise.
2045 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002046int
Fred Drake399739f2000-08-31 05:52:44 +00002047PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002048{
2049 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00002050 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002051 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00002052 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002053 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00002054 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00002055 EXCEPTION_EXECUTE_HANDLER :
2056 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00002057 int errcode = _resetstkoflw();
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +00002058 if (errcode == 0)
Christian Heimes7131fd92008-02-19 14:21:46 +00002059 {
2060 Py_FatalError("Could not reset the stack!");
2061 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002062 }
2063 return 1;
2064}
2065
2066#endif /* WIN32 && _MSC_VER */
2067
2068/* Alternate implementations can be added here... */
2069
2070#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002071
2072
2073/* Wrappers around sigaction() or signal(). */
2074
2075PyOS_sighandler_t
2076PyOS_getsig(int sig)
2077{
2078#ifdef HAVE_SIGACTION
2079 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002080 if (sigaction(sig, NULL, &context) == -1)
2081 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002082 return context.sa_handler;
2083#else
2084 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002085/* Special signal handling for the secure CRT in Visual Studio 2005 */
2086#if defined(_MSC_VER) && _MSC_VER >= 1400
2087 switch (sig) {
2088 /* Only these signals are valid */
2089 case SIGINT:
2090 case SIGILL:
2091 case SIGFPE:
2092 case SIGSEGV:
2093 case SIGTERM:
2094 case SIGBREAK:
2095 case SIGABRT:
2096 break;
2097 /* Don't call signal() with other values or it will assert */
2098 default:
2099 return SIG_ERR;
2100 }
2101#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002102 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002103 if (handler != SIG_ERR)
2104 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002105 return handler;
2106#endif
2107}
2108
2109PyOS_sighandler_t
2110PyOS_setsig(int sig, PyOS_sighandler_t handler)
2111{
2112#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002113 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002114 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002115 sigemptyset(&context.sa_mask);
2116 context.sa_flags = 0;
2117 if (sigaction(sig, &context, &ocontext) == -1)
2118 return SIG_ERR;
2119 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002120#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002121 PyOS_sighandler_t oldhandler;
2122 oldhandler = signal(sig, handler);
2123#ifdef HAVE_SIGINTERRUPT
2124 siginterrupt(sig, 1);
2125#endif
2126 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002127#endif
2128}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002129
2130/* Deprecated C API functions still provided for binary compatiblity */
2131
2132#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002133PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002134PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2135{
2136 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2137}
2138
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002139#undef PyParser_SimpleParseString
2140PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002141PyParser_SimpleParseString(const char *str, int start)
2142{
2143 return PyParser_SimpleParseStringFlags(str, start, 0);
2144}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002145
2146#undef PyRun_AnyFile
2147PyAPI_FUNC(int)
2148PyRun_AnyFile(FILE *fp, const char *name)
2149{
2150 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2151}
2152
2153#undef PyRun_AnyFileEx
2154PyAPI_FUNC(int)
2155PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2156{
2157 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2158}
2159
2160#undef PyRun_AnyFileFlags
2161PyAPI_FUNC(int)
2162PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2163{
2164 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2165}
2166
2167#undef PyRun_File
2168PyAPI_FUNC(PyObject *)
2169PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2170{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002171 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002172}
2173
2174#undef PyRun_FileEx
2175PyAPI_FUNC(PyObject *)
2176PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2177{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002178 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002179}
2180
2181#undef PyRun_FileFlags
2182PyAPI_FUNC(PyObject *)
2183PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2184 PyCompilerFlags *flags)
2185{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002186 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002187}
2188
2189#undef PyRun_SimpleFile
2190PyAPI_FUNC(int)
2191PyRun_SimpleFile(FILE *f, const char *p)
2192{
2193 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2194}
2195
2196#undef PyRun_SimpleFileEx
2197PyAPI_FUNC(int)
2198PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2199{
2200 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2201}
2202
2203
2204#undef PyRun_String
2205PyAPI_FUNC(PyObject *)
2206PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2207{
2208 return PyRun_StringFlags(str, s, g, l, NULL);
2209}
2210
2211#undef PyRun_SimpleString
2212PyAPI_FUNC(int)
2213PyRun_SimpleString(const char *s)
2214{
2215 return PyRun_SimpleStringFlags(s, NULL);
2216}
2217
2218#undef Py_CompileString
2219PyAPI_FUNC(PyObject *)
2220Py_CompileString(const char *str, const char *p, int s)
2221{
2222 return Py_CompileStringFlags(str, p, s, NULL);
2223}
2224
2225#undef PyRun_InteractiveOne
2226PyAPI_FUNC(int)
2227PyRun_InteractiveOne(FILE *f, const char *p)
2228{
2229 return PyRun_InteractiveOneFlags(f, p, NULL);
2230}
2231
2232#undef PyRun_InteractiveLoop
2233PyAPI_FUNC(int)
2234PyRun_InteractiveLoop(FILE *f, const char *p)
2235{
2236 return PyRun_InteractiveLoopFlags(f, p, NULL);
2237}
2238
2239#ifdef __cplusplus
2240}
2241#endif