blob: 124eaf095d0da5664bf1045bc07cd0cc7a596acf [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000021
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000025
Martin v. Löwis73d538b2003-03-05 15:13:47 +000026#ifdef HAVE_LANGINFO_H
27#include <locale.h>
28#include <langinfo.h>
29#endif
30
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000031#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000032#undef BYTE
33#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000034#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000035#endif
36
Neal Norwitz4281cef2006-03-04 19:58:13 +000037#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000038#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000039#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000040#define PRINT_TOTAL_REFS() fprintf(stderr, \
41 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
42 _Py_GetRefTotal())
43#endif
44
45#ifdef __cplusplus
46extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000047#endif
48
Martin v. Löwis790465f2008-04-05 20:41:37 +000049extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000050
Guido van Rossum82598051997-03-05 00:20:32 +000051extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000052
Guido van Rossumb73cc041993-11-01 16:28:59 +000053/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000054static void initmain(void);
55static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000056static int initstdio(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000057static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000058 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000059static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000060 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000061static void err_input(perrdetail *);
62static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000063static void call_py_exitfuncs(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000065extern void _PyUnicode_Init(void);
66extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000067extern int _PyLong_Init(void);
68extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000069
Mark Hammond8d98d2c2003-04-19 15:41:53 +000070#ifdef WITH_THREAD
71extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
72extern void _PyGILState_Fini(void);
73#endif /* WITH_THREAD */
74
Guido van Rossum82598051997-03-05 00:20:32 +000075int Py_DebugFlag; /* Needed by parser.c */
76int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000077int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000078int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000079int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000080int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000081int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000082int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000083int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000084int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000085
Mark Hammonda43fd0c2003-02-19 00:33:33 +000086/* Reference to 'warnings' module, to avoid importing it
Mark Hammondedd07732003-07-15 23:03:55 +000087 on the fly when the import lock may be held. See 683658/771097
Mark Hammonda43fd0c2003-02-19 00:33:33 +000088*/
Mark Hammondedd07732003-07-15 23:03:55 +000089static PyObject *warnings_module = NULL;
90
91/* Returns a borrowed reference to the 'warnings' module, or NULL.
92 If the module is returned, it is guaranteed to have been obtained
93 without acquiring the import lock
94*/
Martin v. Löwisa2c17c52003-08-09 09:47:11 +000095PyObject *PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000096{
97 PyObject *typ, *val, *tb;
98 PyObject *all_modules;
99 /* If we managed to get the module at init time, just use it */
100 if (warnings_module)
101 return warnings_module;
102 /* If it wasn't available at init time, it may be available
103 now in sys.modules (common scenario is frozen apps: import
104 at init time fails, but the frozen init code sets up sys.path
105 correctly, then does an implicit import of warnings for us
106 */
107 /* Save and restore any exceptions */
108 PyErr_Fetch(&typ, &val, &tb);
109
Mark Hammond5f4e8ca2003-07-16 01:54:38 +0000110 all_modules = PySys_GetObject("modules");
Mark Hammondedd07732003-07-15 23:03:55 +0000111 if (all_modules) {
112 warnings_module = PyDict_GetItemString(all_modules, "warnings");
113 /* We keep a ref in the global */
114 Py_XINCREF(warnings_module);
115 }
116 PyErr_Restore(typ, val, tb);
117 return warnings_module;
118}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000119
Guido van Rossum25ce5661997-08-02 03:10:38 +0000120static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000121
Thomas Wouters7e474022000-07-16 12:04:32 +0000122/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000123
124int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000125Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000126{
127 return initialized;
128}
129
Guido van Rossum25ce5661997-08-02 03:10:38 +0000130/* Global initializations. Can be undone by Py_Finalize(). Don't
131 call this twice without an intervening Py_Finalize() call. When
132 initializations fail, a fatal error is issued and the function does
133 not return. On return, the first thread and interpreter state have
134 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000135
Guido van Rossum25ce5661997-08-02 03:10:38 +0000136 Locking: you must hold the interpreter lock while calling this.
137 (If the lock has not yet been initialized, that's equivalent to
138 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000139
Guido van Rossum25ce5661997-08-02 03:10:38 +0000140*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000141
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000142static int
143add_flag(int flag, const char *envs)
144{
145 int env = atoi(envs);
146 if (flag < env)
147 flag = env;
148 if (flag < 1)
149 flag = 1;
150 return flag;
151}
152
Guido van Rossuma027efa1997-05-05 20:56:21 +0000153void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000154Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000155{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000156 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000157 PyThreadState *tstate;
Guido van Rossum826d8972007-10-30 18:34:07 +0000158 PyObject *bimod, *sysmod, *pstderr;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000159 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000160#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000161 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000162#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000163 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000164
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000165 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000166 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000167 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000168
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000169#ifdef HAVE_SETLOCALE
170 /* Set up the LC_CTYPE locale, so we can obtain
171 the locale's charset without having to switch
172 locales. */
173 setlocale(LC_CTYPE, "");
174#endif
175
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000176 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000177 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000178 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000179 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000180 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000181 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Christian Heimes790c8232008-01-07 21:14:23 +0000182 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
183 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000184
Guido van Rossuma027efa1997-05-05 20:56:21 +0000185 interp = PyInterpreterState_New();
186 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000187 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000188
Guido van Rossuma027efa1997-05-05 20:56:21 +0000189 tstate = PyThreadState_New(interp);
190 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000191 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000192 (void) PyThreadState_Swap(tstate);
193
Guido van Rossum70d893a2001-08-16 08:21:42 +0000194 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000195
Neal Norwitzb2501f42002-12-31 03:42:13 +0000196 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000197 Py_FatalError("Py_Initialize: can't init frames");
198
Guido van Rossumddefaf32007-01-14 03:31:43 +0000199 if (!_PyLong_Init())
200 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000201
Neal Norwitz6968b052007-02-27 19:02:19 +0000202 if (!PyBytes_Init())
203 Py_FatalError("Py_Initialize: can't init bytes");
204
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000205 _PyFloat_Init();
206
Guido van Rossum25ce5661997-08-02 03:10:38 +0000207 interp->modules = PyDict_New();
208 if (interp->modules == NULL)
209 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000210 interp->modules_reloading = PyDict_New();
211 if (interp->modules_reloading == NULL)
212 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000213
Guido van Rossumc94044c2000-03-10 23:03:54 +0000214 /* Init Unicode implementation; relies on the codec registry */
215 _PyUnicode_Init();
216
Barry Warsawf242aa02000-05-25 23:09:49 +0000217 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000218 if (bimod == NULL)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000219 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000220 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000221 if (interp->builtins == NULL)
222 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000223 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000224
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000225 /* initialize builtin exceptions */
226 _PyExc_Init();
227
Guido van Rossum25ce5661997-08-02 03:10:38 +0000228 sysmod = _PySys_Init();
229 if (sysmod == NULL)
230 Py_FatalError("Py_Initialize: can't initialize sys");
231 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000232 if (interp->sysdict == NULL)
233 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000234 Py_INCREF(interp->sysdict);
235 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000236 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000237 PyDict_SetItemString(interp->sysdict, "modules",
238 interp->modules);
239
Guido van Rossum826d8972007-10-30 18:34:07 +0000240 /* Set up a preliminary stderr printer until we have enough
241 infrastructure for the io module in place. */
242 pstderr = PyFile_NewStdPrinter(fileno(stderr));
243 if (pstderr == NULL)
244 Py_FatalError("Py_Initialize: can't set preliminary stderr");
245 PySys_SetObject("stderr", pstderr);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000246 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000247
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000248 _PyImport_Init();
249
Barry Warsaw035574d1997-08-29 22:07:17 +0000250 /* phase 2 of builtins */
Georg Brandl1a3284e2007-12-02 09:40:06 +0000251 _PyImport_FixupExtension("builtins", "builtins");
Barry Warsaw035574d1997-08-29 22:07:17 +0000252
Just van Rossum52e14d62002-12-30 22:08:05 +0000253 _PyImportHooks_Init();
254
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000255 if (install_sigs)
256 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000257
258 initmain(); /* Module __main__ */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000259 if (initstdio() < 0)
260 Py_FatalError(
261 "Py_Initialize: can't initialize sys standard streams");
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000262 if (!Py_NoSiteFlag)
263 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000264
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000265 /* auto-thread-state API, if available */
266#ifdef WITH_THREAD
267 _PyGILState_Init(interp, tstate);
268#endif /* WITH_THREAD */
269
Mark Hammondedd07732003-07-15 23:03:55 +0000270 warnings_module = PyImport_ImportModule("warnings");
Guido van Rossum98297ee2007-11-06 21:34:58 +0000271 if (!warnings_module) {
Mark Hammondedd07732003-07-15 23:03:55 +0000272 PyErr_Clear();
Guido van Rossum98297ee2007-11-06 21:34:58 +0000273 }
274 else {
275 PyObject *o;
276 char *action[8];
277
278 if (Py_BytesWarningFlag > 1)
279 *action = "error";
280 else if (Py_BytesWarningFlag)
281 *action = "default";
282 else
283 *action = "ignore";
284
285 o = PyObject_CallMethod(warnings_module,
286 "simplefilter", "sO",
287 *action, PyExc_BytesWarning);
288 if (o == NULL)
289 Py_FatalError("Py_Initialize: can't initialize"
290 "warning filter for BytesWarning.");
291 Py_DECREF(o);
292 }
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000293
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000294#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000295 /* On Unix, set the file system encoding according to the
296 user's preference, if the CODESET names a well-known
297 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000298 initialized by other means. Also set the encoding of
299 stdin and stdout if these are terminals. */
300
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000301 codeset = nl_langinfo(CODESET);
302 if (codeset && *codeset) {
303 PyObject *enc = PyCodec_Encoder(codeset);
304 if (enc) {
305 codeset = strdup(codeset);
306 Py_DECREF(enc);
307 } else {
308 codeset = NULL;
309 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000310 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000311 } else
312 codeset = NULL;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000313
314 if (codeset) {
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000315 if (!Py_FileSystemDefaultEncoding)
316 Py_FileSystemDefaultEncoding = codeset;
317 else
318 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000319 }
320#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000321}
322
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000323void
324Py_Initialize(void)
325{
326 Py_InitializeEx(1);
327}
328
329
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000330#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000331extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000332#endif
333
Guido van Rossume8432ac2007-07-09 15:04:50 +0000334/* Flush stdout and stderr */
335
Neal Norwitz2bad9702007-08-27 06:19:22 +0000336static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000337flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000338{
339 PyObject *fout = PySys_GetObject("stdout");
340 PyObject *ferr = PySys_GetObject("stderr");
341 PyObject *tmp;
342
Christian Heimes2be03732007-11-15 02:26:46 +0000343 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000344 tmp = PyObject_CallMethod(fout, "flush", "");
345 if (tmp == NULL)
346 PyErr_Clear();
347 else
348 Py_DECREF(tmp);
349 }
350
Christian Heimes2be03732007-11-15 02:26:46 +0000351 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000352 tmp = PyObject_CallMethod(ferr, "flush", "");
353 if (tmp == NULL)
354 PyErr_Clear();
355 else
356 Py_DECREF(tmp);
357 }
358}
359
Guido van Rossum25ce5661997-08-02 03:10:38 +0000360/* Undo the effect of Py_Initialize().
361
362 Beware: if multiple interpreter and/or thread states exist, these
363 are not wiped out; only the current thread and interpreter state
364 are deleted. But since everything else is deleted, those other
365 interpreter and thread states should no longer be used.
366
367 (XXX We should do better, e.g. wipe out all interpreters and
368 threads.)
369
370 Locking: as above.
371
372*/
373
374void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000375Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000376{
377 PyInterpreterState *interp;
378 PyThreadState *tstate;
379
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000380 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000381 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000382
Tim Peters384fd102001-01-21 03:40:37 +0000383 /* The interpreter is still entirely intact at this point, and the
384 * exit funcs may be relying on that. In particular, if some thread
385 * or exit func is still waiting to do an import, the import machinery
386 * expects Py_IsInitialized() to return true. So don't say the
387 * interpreter is uninitialized until after the exit funcs have run.
388 * Note that Threading.py uses an exit func to do a join on all the
389 * threads created thru it, so this also protects pending imports in
390 * the threads created via Threading.
391 */
Collin Winter670e6922007-03-21 02:57:17 +0000392 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000393 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000394
Guido van Rossume8432ac2007-07-09 15:04:50 +0000395 /* Flush stdout+stderr */
396 flush_std_files();
397
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000398 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000399 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000400 interp = tstate->interp;
401
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000402 /* Disable signal handling */
403 PyOS_FiniInterrupts();
404
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000405 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000406 Py_XDECREF(warnings_module);
407 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000408
Christian Heimes26855632008-01-27 23:50:43 +0000409 /* Clear type lookup cache */
410 PyType_ClearCache();
411
Guido van Rossume13ddc92003-04-17 17:29:22 +0000412 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000413 * before all modules are destroyed.
414 * XXX If a __del__ or weakref callback is triggered here, and tries to
415 * XXX import a module, bad things can happen, because Python no
416 * XXX longer believes it's initialized.
417 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
418 * XXX is easy to provoke that way. I've also seen, e.g.,
419 * XXX Exception exceptions.ImportError: 'No module named sha'
420 * XXX in <function callback at 0x008F5718> ignored
421 * XXX but I'm unclear on exactly how that one happens. In any case,
422 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000423 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000424 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000425#ifdef COUNT_ALLOCS
426 /* With COUNT_ALLOCS, it helps to run GC multiple times:
427 each collection might release some types from the type
428 list, so they become garbage. */
429 while (PyGC_Collect() > 0)
430 /* nothing */;
431#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000432
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000433 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000434 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000435
Guido van Rossume8432ac2007-07-09 15:04:50 +0000436 /* Flush stdout+stderr (again, in case more was printed) */
437 flush_std_files();
438
Guido van Rossume13ddc92003-04-17 17:29:22 +0000439 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000440 * new-style class definitions, for example.
441 * XXX This is disabled because it caused too many problems. If
442 * XXX a __del__ or weakref callback triggers here, Python code has
443 * XXX a hard time running, because even the sys module has been
444 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
445 * XXX One symptom is a sequence of information-free messages
446 * XXX coming from threads (if a __del__ or callback is invoked,
447 * XXX other threads can execute too, and any exception they encounter
448 * XXX triggers a comedy of errors as subsystem after subsystem
449 * XXX fails to find what it *expects* to find in sys to help report
450 * XXX the exception and consequent unexpected failures). I've also
451 * XXX seen segfaults then, after adding print statements to the
452 * XXX Python code getting called.
453 */
454#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000455 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000456#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000457
Guido van Rossum1707aad1997-12-08 23:43:45 +0000458 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
459 _PyImport_Fini();
460
461 /* Debugging stuff */
462#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000463 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000464#endif
465
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000466 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000467
Tim Peters9cf25ce2003-04-17 15:21:01 +0000468#ifdef Py_TRACE_REFS
469 /* Display all objects still alive -- this can invoke arbitrary
470 * __repr__ overrides, so requires a mostly-intact interpreter.
471 * Alas, a lot of stuff may still be alive now that will be cleaned
472 * up later.
473 */
Tim Peters269b2a62003-04-17 19:52:29 +0000474 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000475 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000476#endif /* Py_TRACE_REFS */
477
Guido van Rossumd922fa42003-04-15 14:10:09 +0000478 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000479 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000480
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000481 /* Now we decref the exception classes. After this point nothing
482 can raise an exception. That's okay, because each Fini() method
483 below has been checked to make sure no exceptions are ever
484 raised.
485 */
486
487 _PyExc_Fini();
488
Christian Heimes7d2ff882007-11-30 14:35:04 +0000489 /* Cleanup auto-thread-state */
490#ifdef WITH_THREAD
491 _PyGILState_Fini();
492#endif /* WITH_THREAD */
493
Guido van Rossumd922fa42003-04-15 14:10:09 +0000494 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000495 PyThreadState_Swap(NULL);
496 PyInterpreterState_Delete(interp);
497
Guido van Rossumd922fa42003-04-15 14:10:09 +0000498 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000499 PyMethod_Fini();
500 PyFrame_Fini();
501 PyCFunction_Fini();
502 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000503 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000504 PySet_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000505 PyString_Fini();
Neal Norwitz6968b052007-02-27 19:02:19 +0000506 PyBytes_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000507 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000508 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000509 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000510
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000511 /* Cleanup Unicode implementation */
512 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000513
Christian Heimesc8967002007-11-30 10:18:26 +0000514 /* reset file system default encoding */
515 if (!Py_HasFileSystemDefaultEncoding) {
516 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000517 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000518 }
519
Guido van Rossumcc283f51997-08-05 02:22:03 +0000520 /* XXX Still allocated:
521 - various static ad-hoc pointers to interned strings
522 - int and float free list blocks
523 - whatever various modules and libraries allocate
524 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000525
526 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000527
Tim Peters269b2a62003-04-17 19:52:29 +0000528#ifdef Py_TRACE_REFS
529 /* Display addresses (& refcnts) of all objects still alive.
530 * An address can be used to find the repr of the object, printed
531 * above by _Py_PrintReferences.
532 */
533 if (Py_GETENV("PYTHONDUMPREFS"))
534 _Py_PrintReferenceAddresses(stderr);
535#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000536#ifdef PYMALLOC_DEBUG
537 if (Py_GETENV("PYTHONMALLOCSTATS"))
538 _PyObject_DebugMallocStats();
539#endif
540
Guido van Rossumcc283f51997-08-05 02:22:03 +0000541 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000542}
543
544/* Create and initialize a new interpreter and thread, and return the
545 new thread. This requires that Py_Initialize() has been called
546 first.
547
548 Unsuccessful initialization yields a NULL pointer. Note that *no*
549 exception information is available even in this case -- the
550 exception information is held in the thread, and there is no
551 thread.
552
553 Locking: as above.
554
555*/
556
557PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000558Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559{
560 PyInterpreterState *interp;
561 PyThreadState *tstate, *save_tstate;
562 PyObject *bimod, *sysmod;
563
564 if (!initialized)
565 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
566
567 interp = PyInterpreterState_New();
568 if (interp == NULL)
569 return NULL;
570
571 tstate = PyThreadState_New(interp);
572 if (tstate == NULL) {
573 PyInterpreterState_Delete(interp);
574 return NULL;
575 }
576
577 save_tstate = PyThreadState_Swap(tstate);
578
579 /* XXX The following is lax in error checking */
580
581 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000582 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000583
Georg Brandl1a3284e2007-12-02 09:40:06 +0000584 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000586 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000587 if (interp->builtins == NULL)
588 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000589 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590 }
591 sysmod = _PyImport_FindExtension("sys", "sys");
592 if (bimod != NULL && sysmod != NULL) {
593 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000594 if (interp->sysdict == NULL)
595 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596 Py_INCREF(interp->sysdict);
597 PySys_SetPath(Py_GetPath());
598 PyDict_SetItemString(interp->sysdict, "modules",
599 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000600 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000602 if (!Py_NoSiteFlag)
603 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000604 }
605
606 if (!PyErr_Occurred())
607 return tstate;
608
Thomas Wouters89f507f2006-12-13 04:49:30 +0000609handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610 /* Oops, it didn't work. Undo it all. */
611
612 PyErr_Print();
613 PyThreadState_Clear(tstate);
614 PyThreadState_Swap(save_tstate);
615 PyThreadState_Delete(tstate);
616 PyInterpreterState_Delete(interp);
617
618 return NULL;
619}
620
621/* Delete an interpreter and its last thread. This requires that the
622 given thread state is current, that the thread has no remaining
623 frames, and that it is its interpreter's only remaining thread.
624 It is a fatal error to violate these constraints.
625
626 (Py_Finalize() doesn't have these constraints -- it zaps
627 everything, regardless.)
628
629 Locking: as above.
630
631*/
632
633void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000634Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635{
636 PyInterpreterState *interp = tstate->interp;
637
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000638 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000639 Py_FatalError("Py_EndInterpreter: thread is not current");
640 if (tstate->frame != NULL)
641 Py_FatalError("Py_EndInterpreter: thread still has a frame");
642 if (tstate != interp->tstate_head || tstate->next != NULL)
643 Py_FatalError("Py_EndInterpreter: not the last thread");
644
645 PyImport_Cleanup();
646 PyInterpreterState_Clear(interp);
647 PyThreadState_Swap(NULL);
648 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000649}
650
Martin v. Löwis790465f2008-04-05 20:41:37 +0000651static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000652
653void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000654Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000655{
656 if (pn && *pn)
657 progname = pn;
658}
659
Martin v. Löwis790465f2008-04-05 20:41:37 +0000660wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000661Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000662{
663 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000664}
665
Martin v. Löwis790465f2008-04-05 20:41:37 +0000666static wchar_t *default_home = NULL;
667static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000668
669void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000670Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000671{
672 default_home = home;
673}
674
Martin v. Löwis790465f2008-04-05 20:41:37 +0000675wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000676Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000677{
Martin v. Löwis790465f2008-04-05 20:41:37 +0000678 wchar_t *home = default_home;
679 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
680 char* chome = Py_GETENV("PYTHONHOME");
681 if (chome) {
682 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
683 if (r != (size_t)-1 && r <= PATH_MAX)
684 home = env_home;
685 }
686
687 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000688 return home;
689}
690
Guido van Rossum6135a871995-01-09 17:53:26 +0000691/* Create __main__ module */
692
693static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000694initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000695{
Guido van Rossum82598051997-03-05 00:20:32 +0000696 PyObject *m, *d;
697 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000698 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000699 Py_FatalError("can't create __main__ module");
700 d = PyModule_GetDict(m);
701 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000702 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000703 if (bimod == NULL ||
704 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000705 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000706 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000707 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000708}
709
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000710/* Import the site module (not into __main__ though) */
711
712static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000713initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000714{
715 PyObject *m, *f;
716 m = PyImport_ImportModule("site");
717 if (m == NULL) {
718 f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +0000719 if (f == NULL || f == Py_None)
720 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000721 if (Py_VerboseFlag) {
722 PyFile_WriteString(
723 "'import site' failed; traceback:\n", f);
724 PyErr_Print();
725 }
726 else {
727 PyFile_WriteString(
728 "'import site' failed; use -v for traceback\n", f);
729 PyErr_Clear();
730 }
731 }
732 else {
733 Py_DECREF(m);
734 }
735}
736
Georg Brandl1a3284e2007-12-02 09:40:06 +0000737/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000738static int
739initstdio(void)
740{
741 PyObject *iomod = NULL, *wrapper;
742 PyObject *bimod = NULL;
743 PyObject *m;
744 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000745 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000746 PyObject * encoding_attr;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000747
748 /* Hack to avoid a nasty recursion issue when Python is invoked
749 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
750 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
751 goto error;
752 }
753 Py_DECREF(m);
754
755 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
756 goto error;
757 }
758 Py_DECREF(m);
759
Georg Brandl1a3284e2007-12-02 09:40:06 +0000760 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000761 goto error;
762 }
763
764 if (!(iomod = PyImport_ImportModule("io"))) {
765 goto error;
766 }
767 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
768 goto error;
769 }
770
Georg Brandl1a3284e2007-12-02 09:40:06 +0000771 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000772 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
773 goto error;
774 }
775
776 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000777 fd = fileno(stdin);
778 /* Under some conditions stdin, stdout and stderr may not be connected
779 * and fileno() may point to an invalid file descriptor. For example
780 * GUI apps don't have valid standard streams by default.
781 */
782 if (fd < 0) {
783#ifdef MS_WINDOWS
784 std = Py_None;
785 Py_INCREF(std);
786#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000787 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000788#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000789 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000790 else {
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000791 if (!(std = PyFile_FromFd(fd, "<stdin>", "r", -1, NULL, NULL,
Christian Heimes58cb1b82007-11-13 02:19:40 +0000792 "\n", 0))) {
793 goto error;
794 }
795 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000796 PySys_SetObject("__stdin__", std);
797 PySys_SetObject("stdin", std);
798 Py_DECREF(std);
799
800 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000801 fd = fileno(stdout);
802 if (fd < 0) {
803#ifdef MS_WINDOWS
804 std = Py_None;
805 Py_INCREF(std);
806#else
807 goto error;
808#endif
809 }
810 else {
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000811 if (!(std = PyFile_FromFd(fd, "<stdout>", "w", -1, NULL, NULL,
Christian Heimes58cb1b82007-11-13 02:19:40 +0000812 "\n", 0))) {
813 goto error;
814 }
815 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000816 PySys_SetObject("__stdout__", std);
817 PySys_SetObject("stdout", std);
818 Py_DECREF(std);
819
Guido van Rossum98297ee2007-11-06 21:34:58 +0000820#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000821 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000822 fd = fileno(stderr);
823 if (fd < 0) {
824#ifdef MS_WINDOWS
825 std = Py_None;
826 Py_INCREF(std);
827#else
828 goto error;
829#endif
830 }
831 else {
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000832 if (!(std = PyFile_FromFd(fd, "<stderr>", "w", -1, NULL, NULL,
Christian Heimes58cb1b82007-11-13 02:19:40 +0000833 "\n", 0))) {
834 goto error;
835 }
836 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000837
838 /* Same as hack above, pre-import stderr's codec to avoid recursion
839 when import.c tries to write to stderr in verbose mode. */
840 encoding_attr = PyObject_GetAttrString(std, "encoding");
841 if (encoding_attr != NULL) {
842 const char * encoding;
843 encoding = PyUnicode_AsString(encoding_attr);
844 if (encoding != NULL) {
845 _PyCodec_Lookup(encoding);
846 }
847 }
848 PyErr_Clear(); /* Not a fatal error if codec isn't available */
849
Christian Heimesdb233082007-11-13 02:34:21 +0000850 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000851 PySys_SetObject("stderr", std);
852 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000853#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000854
Christian Heimes58cb1b82007-11-13 02:19:40 +0000855 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000856 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000857 status = -1;
858 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000859
860 Py_XDECREF(bimod);
861 Py_XDECREF(iomod);
862 return status;
863}
864
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000865/* Parse input from a file and execute it */
866
867int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000868PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000869 PyCompilerFlags *flags)
870{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000871 if (filename == NULL)
872 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000873 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000874 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000875 if (closeit)
876 fclose(fp);
877 return err;
878 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000879 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000880 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000881}
882
883int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000884PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000885{
Guido van Rossum82598051997-03-05 00:20:32 +0000886 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000887 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000888 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000889
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000890 if (flags == NULL) {
891 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000892 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000893 }
Guido van Rossum82598051997-03-05 00:20:32 +0000894 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000895 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000896 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000897 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000898 }
Guido van Rossum82598051997-03-05 00:20:32 +0000899 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000900 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000901 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000902 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000903 }
904 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000905 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000906 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000907 if (ret == E_EOF)
908 return 0;
909 /*
910 if (ret == E_NOMEM)
911 return -1;
912 */
913 }
914}
915
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000916/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000917#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000918 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Guido van Rossum45aecf42006-03-15 04:58:47 +0000919 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000920
Thomas Wouters89f507f2006-12-13 04:49:30 +0000921#if 0
922/* Keep an example of flags with future keyword support. */
923#define PARSER_FLAGS(flags) \
924 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
925 PyPARSE_DONT_IMPLY_DEDENT : 0) \
926 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
927 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
928#endif
929
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000930int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000931PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000932{
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000933 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000934 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +0000935 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000936 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000937 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000938
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000939 if (fp == stdin) {
940 /* Fetch encoding from sys.stdin */
941 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +0000942 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000943 return -1;
944 oenc = PyObject_GetAttrString(v, "encoding");
945 if (!oenc)
946 return -1;
947 enc = PyUnicode_AsString(oenc);
948 }
Guido van Rossum82598051997-03-05 00:20:32 +0000949 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000950 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000951 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000952 if (v == NULL)
953 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000954 else if (PyUnicode_Check(v))
955 ps1 = PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000956 }
Guido van Rossum82598051997-03-05 00:20:32 +0000957 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000958 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000959 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000960 if (w == NULL)
961 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000962 else if (PyUnicode_Check(w))
963 ps2 = PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000964 }
Neal Norwitz9589ee22006-03-04 19:01:22 +0000965 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000966 if (arena == NULL) {
967 Py_XDECREF(v);
968 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000969 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000970 return -1;
971 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000972 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000973 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000974 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +0000975 Py_XDECREF(v);
976 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000977 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000978 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000979 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000980 if (errcode == E_EOF) {
981 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000982 return E_EOF;
983 }
Guido van Rossum82598051997-03-05 00:20:32 +0000984 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000985 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000986 }
Guido van Rossum82598051997-03-05 00:20:32 +0000987 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000988 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000989 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000990 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000991 }
Guido van Rossum82598051997-03-05 00:20:32 +0000992 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000993 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +0000994 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000995 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000996 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000997 return -1;
998 }
Guido van Rossum82598051997-03-05 00:20:32 +0000999 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001000 return 0;
1001}
1002
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001003/* Check whether a file maybe a pyc file: Look at the extension,
1004 the file type, and, if we may close it, at the first few bytes. */
1005
1006static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001007maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001008{
1009 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1010 return 1;
1011
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001012 /* Only look into the file if we are allowed to close it, since
1013 it then should also be seekable. */
1014 if (closeit) {
1015 /* Read only two bytes of the magic. If the file was opened in
1016 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1017 be read as they are on disk. */
1018 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1019 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001020 /* Mess: In case of -x, the stream is NOT at its start now,
1021 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001022 which makes the current stream position formally undefined,
1023 and a x-platform nightmare.
1024 Unfortunately, we have no direct way to know whether -x
1025 was specified. So we use a terrible hack: if the current
1026 stream position is not 0, we assume -x was specified, and
1027 give up. Bug 132850 on SourceForge spells out the
1028 hopelessness of trying anything else (fseek and ftell
1029 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001030 */
Tim Peters3e876562001-02-11 04:35:39 +00001031 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001032 if (ftell(fp) == 0) {
1033 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001034 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001035 ispyc = 1;
1036 rewind(fp);
1037 }
Tim Peters3e876562001-02-11 04:35:39 +00001038 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001039 }
1040 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001041}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001042
Guido van Rossum0df002c2000-08-27 19:21:52 +00001043int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001044PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001045 PyCompilerFlags *flags)
1046{
Guido van Rossum82598051997-03-05 00:20:32 +00001047 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001048 const char *ext;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001049 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001050
Guido van Rossum82598051997-03-05 00:20:32 +00001051 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001052 if (m == NULL)
1053 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001054 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001055 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001056 PyObject *f;
1057 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001058 if (f == NULL)
1059 return -1;
1060 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1061 Py_DECREF(f);
1062 return -1;
1063 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001064 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001065 Py_DECREF(f);
1066 }
Guido van Rossumfdef2711994-09-14 13:31:04 +00001067 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001068 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001069 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001070 if (closeit)
1071 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001072 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001073 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001074 ret = -1;
1075 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001076 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001077 /* Turn on optimization if a .pyo file is given */
1078 if (strcmp(ext, ".pyo") == 0)
1079 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001080 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001081 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001082 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001083 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001084 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001085 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001086 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001087 ret = -1;
1088 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001089 }
Guido van Rossum82598051997-03-05 00:20:32 +00001090 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001091 ret = 0;
1092 done:
1093 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1094 PyErr_Clear();
1095 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001096}
1097
1098int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001099PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001100{
Guido van Rossum82598051997-03-05 00:20:32 +00001101 PyObject *m, *d, *v;
1102 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001103 if (m == NULL)
1104 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001105 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001106 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001107 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001108 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001109 return -1;
1110 }
Guido van Rossum82598051997-03-05 00:20:32 +00001111 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001112 return 0;
1113}
1114
Barry Warsaw035574d1997-08-29 22:07:17 +00001115static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001116parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1117 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001118{
1119 long hold;
1120 PyObject *v;
1121
1122 /* old style errors */
1123 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001124 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001125 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001126
1127 /* new style errors. `err' is an instance */
1128
1129 if (! (v = PyObject_GetAttrString(err, "msg")))
1130 goto finally;
1131 *message = v;
1132
1133 if (!(v = PyObject_GetAttrString(err, "filename")))
1134 goto finally;
1135 if (v == Py_None)
1136 *filename = NULL;
Kurt B. Kaiser43b15092008-01-05 04:32:22 +00001137 else if (! (*filename = PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001138 goto finally;
1139
1140 Py_DECREF(v);
1141 if (!(v = PyObject_GetAttrString(err, "lineno")))
1142 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001143 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001144 Py_DECREF(v);
1145 v = NULL;
1146 if (hold < 0 && PyErr_Occurred())
1147 goto finally;
1148 *lineno = (int)hold;
1149
1150 if (!(v = PyObject_GetAttrString(err, "offset")))
1151 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001152 if (v == Py_None) {
1153 *offset = -1;
1154 Py_DECREF(v);
1155 v = NULL;
1156 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001157 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001158 Py_DECREF(v);
1159 v = NULL;
1160 if (hold < 0 && PyErr_Occurred())
1161 goto finally;
1162 *offset = (int)hold;
1163 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001164
1165 if (!(v = PyObject_GetAttrString(err, "text")))
1166 goto finally;
1167 if (v == Py_None)
1168 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001169 else if (!PyUnicode_Check(v) ||
1170 !(*text = PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001171 goto finally;
1172 Py_DECREF(v);
1173 return 1;
1174
1175finally:
1176 Py_XDECREF(v);
1177 return 0;
1178}
1179
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001180void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001181PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001182{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001183 PyErr_PrintEx(1);
1184}
1185
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001186static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001187print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001188{
1189 char *nl;
1190 if (offset >= 0) {
1191 if (offset > 0 && offset == (int)strlen(text))
1192 offset--;
1193 for (;;) {
1194 nl = strchr(text, '\n');
1195 if (nl == NULL || nl-text >= offset)
1196 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001197 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001198 text = nl+1;
1199 }
1200 while (*text == ' ' || *text == '\t') {
1201 text++;
1202 offset--;
1203 }
1204 }
1205 PyFile_WriteString(" ", f);
1206 PyFile_WriteString(text, f);
1207 if (*text == '\0' || text[strlen(text)-1] != '\n')
1208 PyFile_WriteString("\n", f);
1209 if (offset == -1)
1210 return;
1211 PyFile_WriteString(" ", f);
1212 offset--;
1213 while (offset > 0) {
1214 PyFile_WriteString(" ", f);
1215 offset--;
1216 }
1217 PyFile_WriteString("^\n", f);
1218}
1219
Guido van Rossum66e8e862001-03-23 17:54:43 +00001220static void
1221handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001222{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001223 PyObject *exception, *value, *tb;
1224 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001225
Guido van Rossumd8faa362007-04-27 19:54:29 +00001226 if (Py_InspectFlag)
1227 /* Don't exit if -i flag was given. This flag is set to 0
1228 * when entering interactive mode for inspecting. */
1229 return;
1230
Guido van Rossum66e8e862001-03-23 17:54:43 +00001231 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001232 fflush(stdout);
1233 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001234 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001235 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001236 /* The error code should be in the `code' attribute. */
1237 PyObject *code = PyObject_GetAttrString(value, "code");
1238 if (code) {
1239 Py_DECREF(value);
1240 value = code;
1241 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001242 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001243 }
1244 /* If we failed to dig out the 'code' attribute,
1245 just let the else clause below print the error. */
1246 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001247 if (PyLong_Check(value))
1248 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001249 else {
1250 PyObject_Print(value, stderr, Py_PRINT_RAW);
1251 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001252 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001253 }
Tim Peterscf615b52003-04-19 18:47:02 +00001254 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001255 /* Restore and clear the exception info, in order to properly decref
1256 * the exception, value, and traceback. If we just exit instead,
1257 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1258 * some finalizers from running.
1259 */
Tim Peterscf615b52003-04-19 18:47:02 +00001260 PyErr_Restore(exception, value, tb);
1261 PyErr_Clear();
1262 Py_Exit(exitcode);
1263 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001264}
1265
1266void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001267PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001268{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001269 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001270
1271 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1272 handle_system_exit();
1273 }
Guido van Rossum82598051997-03-05 00:20:32 +00001274 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001275 if (exception == NULL)
1276 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001277 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001278 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001279 return;
Guido van Rossum9d785502006-03-07 18:31:44 +00001280 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001281 if (set_sys_last_vars) {
1282 PySys_SetObject("last_type", exception);
1283 PySys_SetObject("last_value", v);
Guido van Rossumc5724de2007-10-10 21:38:59 +00001284 PySys_SetObject("last_traceback", tb ? tb : Py_None);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001285 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001286 hook = PySys_GetObject("excepthook");
1287 if (hook) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001288 PyObject *args = PyTuple_Pack(3,
Guido van Rossum9d785502006-03-07 18:31:44 +00001289 exception, v, tb ? tb : Py_None);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001290 PyObject *result = PyEval_CallObject(hook, args);
1291 if (result == NULL) {
1292 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001293 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1294 handle_system_exit();
1295 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001296 PyErr_Fetch(&exception2, &v2, &tb2);
1297 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001298 /* It should not be possible for exception2 or v2
1299 to be NULL. However PyErr_Display() can't
1300 tolerate NULLs, so just be safe. */
1301 if (exception2 == NULL) {
1302 exception2 = Py_None;
1303 Py_INCREF(exception2);
1304 }
1305 if (v2 == NULL) {
1306 v2 = Py_None;
1307 Py_INCREF(v2);
1308 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001309 fflush(stdout);
1310 PySys_WriteStderr("Error in sys.excepthook:\n");
1311 PyErr_Display(exception2, v2, tb2);
1312 PySys_WriteStderr("\nOriginal exception was:\n");
1313 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001314 Py_DECREF(exception2);
1315 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001316 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001317 }
1318 Py_XDECREF(result);
1319 Py_XDECREF(args);
1320 } else {
1321 PySys_WriteStderr("sys.excepthook is missing\n");
1322 PyErr_Display(exception, v, tb);
1323 }
1324 Py_XDECREF(exception);
1325 Py_XDECREF(v);
1326 Py_XDECREF(tb);
1327}
1328
Thomas Wouters477c8d52006-05-27 19:21:47 +00001329void
1330PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001331{
1332 int err = 0;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001333 PyObject *f = PySys_GetObject("stderr");
Armin Rigo5d2c6832004-03-22 20:16:58 +00001334 Py_INCREF(value);
Christian Heimes2be03732007-11-15 02:26:46 +00001335 if (f == Py_None) {
1336 /* pass */
1337 }
1338 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001339 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001340 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001341 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001342 else {
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001343 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001344 if (tb && tb != Py_None)
1345 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001346 if (err == 0 &&
Armin Rigo5d2c6832004-03-22 20:16:58 +00001347 PyObject_HasAttrString(value, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001348 {
Guido van Rossum82598051997-03-05 00:20:32 +00001349 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001350 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001351 int lineno, offset;
Armin Rigo5d2c6832004-03-22 20:16:58 +00001352 if (!parse_syntax_error(value, &message, &filename,
Barry Warsaw035574d1997-08-29 22:07:17 +00001353 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001354 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001355 else {
1356 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001357 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001358 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001359 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001360 else
Guido van Rossum82598051997-03-05 00:20:32 +00001361 PyFile_WriteString(filename, f);
1362 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001363 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001364 PyFile_WriteString(buf, f);
1365 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001366 if (text != NULL)
1367 print_error_text(f, offset, text);
Armin Rigo5d2c6832004-03-22 20:16:58 +00001368 Py_DECREF(value);
1369 value = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001370 /* Can't be bothered to check all those
1371 PyFile_WriteString() calls */
1372 if (PyErr_Occurred())
1373 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001374 }
1375 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001376 if (err) {
1377 /* Don't do anything else */
1378 }
Brett Cannonbf364092006-03-01 04:25:17 +00001379 else if (PyExceptionClass_Check(exception)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001380 PyObject* moduleName;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001381 char* className = PyExceptionClass_Name(exception);
1382 if (className != NULL) {
1383 char *dot = strrchr(className, '.');
1384 if (dot != NULL)
1385 className = dot+1;
1386 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001387
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001388 moduleName = PyObject_GetAttrString(exception, "__module__");
Guido van Rossumc5724de2007-10-10 21:38:59 +00001389 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1390 {
1391 Py_DECREF(moduleName);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001392 err = PyFile_WriteString("<unknown>", f);
Guido van Rossumc5724de2007-10-10 21:38:59 +00001393 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001394 else {
Guido van Rossumc5724de2007-10-10 21:38:59 +00001395 char* modstr = PyUnicode_AsString(moduleName);
Georg Brandl1a3284e2007-12-02 09:40:06 +00001396 if (modstr && strcmp(modstr, "builtins"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001397 {
1398 err = PyFile_WriteString(modstr, f);
1399 err += PyFile_WriteString(".", f);
1400 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001401 Py_DECREF(moduleName);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001402 }
1403 if (err == 0) {
1404 if (className == NULL)
1405 err = PyFile_WriteString("<unknown>", f);
1406 else
Brett Cannonbf364092006-03-01 04:25:17 +00001407 err = PyFile_WriteString(className, f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001408 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001409 }
1410 else
1411 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
Brett Cannon2e63b732006-03-02 18:34:57 +00001412 if (err == 0 && (value != Py_None)) {
Thomas Heller519a0422007-11-15 20:48:54 +00001413 PyObject *s = PyObject_Str(value);
Brett Cannon2e63b732006-03-02 18:34:57 +00001414 /* only print colon if the str() of the
1415 object is not the empty string
1416 */
1417 if (s == NULL)
1418 err = -1;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001419 else if (!PyUnicode_Check(s) ||
1420 PyUnicode_GetSize(s) != 0)
Brett Cannon2e63b732006-03-02 18:34:57 +00001421 err = PyFile_WriteString(": ", f);
1422 if (err == 0)
1423 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1424 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001425 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001426 /* try to write a newline in any case */
1427 err += PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001428 }
Armin Rigo5d2c6832004-03-22 20:16:58 +00001429 Py_DECREF(value);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001430 /* If an error happened here, don't show it.
1431 XXX This is wrong, but too many callers rely on this behavior. */
1432 if (err != 0)
1433 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001434}
1435
Guido van Rossum82598051997-03-05 00:20:32 +00001436PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001437PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001438 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001439{
Neal Norwitze92fba02006-03-04 18:52:26 +00001440 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001441 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001442 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001443 if (arena == NULL)
1444 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001445
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001446 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001447 if (mod != NULL)
1448 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001449 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001450 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001451}
1452
1453PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001454PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001455 PyObject *locals, int closeit, PyCompilerFlags *flags)
1456{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001457 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001458 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001459 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001460 if (arena == NULL)
1461 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001462
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001463 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001464 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001465 if (closeit)
1466 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001467 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001468 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001469 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001470 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001471 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001472 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001473 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001474}
1475
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001476static void
1477flush_io(void)
1478{
1479 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001480 PyObject *type, *value, *traceback;
1481
1482 /* Save the current exception */
1483 PyErr_Fetch(&type, &value, &traceback);
1484
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001485 f = PySys_GetObject("stderr");
1486 if (f != NULL) {
1487 r = PyObject_CallMethod(f, "flush", "");
1488 if (r)
1489 Py_DECREF(r);
1490 else
1491 PyErr_Clear();
1492 }
1493 f = PySys_GetObject("stdout");
1494 if (f != NULL) {
1495 r = PyObject_CallMethod(f, "flush", "");
1496 if (r)
1497 Py_DECREF(r);
1498 else
1499 PyErr_Clear();
1500 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001501
1502 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001503}
1504
Guido van Rossum82598051997-03-05 00:20:32 +00001505static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001506run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001507 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001508{
Guido van Rossum82598051997-03-05 00:20:32 +00001509 PyCodeObject *co;
1510 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001511 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001512 if (co == NULL)
1513 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001514 v = PyEval_EvalCode(co, globals, locals);
1515 Py_DECREF(co);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001516 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001517 return v;
1518}
1519
Guido van Rossum82598051997-03-05 00:20:32 +00001520static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001521run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001522 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001523{
Guido van Rossum82598051997-03-05 00:20:32 +00001524 PyCodeObject *co;
1525 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001526 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001527 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001528
Guido van Rossum82598051997-03-05 00:20:32 +00001529 magic = PyMarshal_ReadLongFromFile(fp);
1530 if (magic != PyImport_GetMagicNumber()) {
1531 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001532 "Bad magic number in .pyc file");
1533 return NULL;
1534 }
Guido van Rossum82598051997-03-05 00:20:32 +00001535 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001536 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001537 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001538 if (v == NULL || !PyCode_Check(v)) {
1539 Py_XDECREF(v);
1540 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001541 "Bad code object in .pyc file");
1542 return NULL;
1543 }
Guido van Rossum82598051997-03-05 00:20:32 +00001544 co = (PyCodeObject *)v;
1545 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001546 if (v && flags)
1547 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001548 Py_DECREF(co);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001549 flush_io();
Guido van Rossumfdef2711994-09-14 13:31:04 +00001550 return v;
1551}
1552
Guido van Rossum82598051997-03-05 00:20:32 +00001553PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001554Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001555 PyCompilerFlags *flags)
1556{
Guido van Rossum82598051997-03-05 00:20:32 +00001557 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001558 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001559 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001560 if (arena == NULL)
1561 return NULL;
1562
1563 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001564 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001565 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001566 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001567 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001568 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001569 PyObject *result = PyAST_mod2obj(mod);
1570 PyArena_Free(arena);
1571 return result;
1572 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001573 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001574 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001575 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001576}
1577
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001578struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001579Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001580{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001581 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001582 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001583 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001584 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001585 if (arena == NULL)
1586 return NULL;
1587
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001588 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001589 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001590 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001591 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001592 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001593 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001594 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001595 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001596 return st;
1597}
1598
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001599/* Preferred access to parser is through AST. */
1600mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001601PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001602 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001603{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001604 mod_ty mod;
1605 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001606 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001607
1608 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001609 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001610 &iflags);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001611 if (n) {
Christian Heimes4d6ec852008-03-26 22:34:47 +00001612 if (flags) {
1613 flags->cf_flags |= iflags & PyCF_MASK;
1614 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001615 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001616 PyNode_Free(n);
1617 return mod;
1618 }
1619 else {
1620 err_input(&err);
1621 return NULL;
1622 }
1623}
1624
1625mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001626PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1627 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001628 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001629 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001630{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001631 mod_ty mod;
1632 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001633 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001634
Christian Heimes4d6ec852008-03-26 22:34:47 +00001635 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001636 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001637 start, ps1, ps2, &err, &iflags);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001638 if (n) {
Christian Heimes4d6ec852008-03-26 22:34:47 +00001639 if (flags) {
1640 flags->cf_flags |= iflags & PyCF_MASK;
1641 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001642 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001643 PyNode_Free(n);
1644 return mod;
1645 }
1646 else {
1647 err_input(&err);
1648 if (errcode)
1649 *errcode = err.error;
1650 return NULL;
1651 }
1652}
1653
Guido van Rossuma110aa61994-08-29 12:50:44 +00001654/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001655
Guido van Rossuma110aa61994-08-29 12:50:44 +00001656node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001657PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001658{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001659 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001660 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1661 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001662 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001663 if (n == NULL)
1664 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001665
Guido van Rossuma110aa61994-08-29 12:50:44 +00001666 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001667}
1668
Guido van Rossuma110aa61994-08-29 12:50:44 +00001669/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001670
Guido van Rossuma110aa61994-08-29 12:50:44 +00001671node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001672PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001673{
Tim Petersfe2127d2001-07-16 05:37:24 +00001674 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001675 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1676 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001677 if (n == NULL)
1678 err_input(&err);
1679 return n;
1680}
1681
1682node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001683PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001684 int start, int flags)
1685{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001686 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001687 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1688 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001689 if (n == NULL)
1690 err_input(&err);
1691 return n;
1692}
1693
1694node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001695PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001696{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001697 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001698}
1699
Guido van Rossum66ebd912003-04-17 16:02:26 +00001700/* May want to move a more generalized form of this to parsetok.c or
1701 even parser modules. */
1702
1703void
1704PyParser_SetError(perrdetail *err)
1705{
1706 err_input(err);
1707}
1708
Guido van Rossuma110aa61994-08-29 12:50:44 +00001709/* Set the error appropriate to the given input error code (see errcode.h) */
1710
1711static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001712err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001713{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001714 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001715 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001716 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001717 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001718 switch (err->error) {
1719 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001720 errtype = PyExc_IndentationError;
1721 if (err->expected == INDENT)
1722 msg = "expected an indented block";
1723 else if (err->token == INDENT)
1724 msg = "unexpected indent";
1725 else if (err->token == DEDENT)
1726 msg = "unexpected unindent";
1727 else {
1728 errtype = PyExc_SyntaxError;
1729 msg = "invalid syntax";
1730 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001731 break;
1732 case E_TOKEN:
1733 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001734 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001735 case E_EOFS:
1736 msg = "EOF while scanning triple-quoted string";
1737 break;
1738 case E_EOLS:
1739 msg = "EOL while scanning single-quoted string";
1740 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001741 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001742 if (!PyErr_Occurred())
1743 PyErr_SetNone(PyExc_KeyboardInterrupt);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001744 return;
1745 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001746 PyErr_NoMemory();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001747 return;
1748 case E_EOF:
1749 msg = "unexpected EOF while parsing";
1750 break;
Fred Drake85f36392000-07-11 17:53:00 +00001751 case E_TABSPACE:
1752 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001753 msg = "inconsistent use of tabs and spaces in indentation";
1754 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001755 case E_OVERFLOW:
1756 msg = "expression too long";
1757 break;
Fred Drake85f36392000-07-11 17:53:00 +00001758 case E_DEDENT:
1759 errtype = PyExc_IndentationError;
1760 msg = "unindent does not match any outer indentation level";
1761 break;
1762 case E_TOODEEP:
1763 errtype = PyExc_IndentationError;
1764 msg = "too many levels of indentation";
1765 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001766 case E_DECODE: {
1767 PyObject *type, *value, *tb;
1768 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001769 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001770 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001771 if (u != NULL) {
Guido van Rossumc5724de2007-10-10 21:38:59 +00001772 msg = PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001773 }
1774 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001775 if (msg == NULL)
1776 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001777 Py_XDECREF(type);
1778 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001779 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001780 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001781 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001782 case E_LINECONT:
1783 msg = "unexpected character after line continuation character";
1784 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001785
1786 case E_IDENTIFIER:
1787 msg = "invalid character in identifier";
1788 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001789 default:
1790 fprintf(stderr, "error=%d\n", err->error);
1791 msg = "unknown parsing error";
1792 break;
1793 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001794 /* err->text may not be UTF-8 in case of decoding errors.
1795 Explicitly convert to an object. */
1796 if (!err->text) {
1797 errtext = Py_None;
1798 Py_INCREF(Py_None);
1799 } else {
1800 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1801 "replace");
1802 }
1803 v = Py_BuildValue("(ziiN)", err->filename,
1804 err->lineno, err->offset, errtext);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001805 if (err->text != NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001806 PyObject_FREE(err->text);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807 err->text = NULL;
1808 }
1809 w = NULL;
1810 if (v != NULL)
1811 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001812 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001813 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001814 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001815 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001816}
1817
1818/* Print fatal error message and abort */
1819
1820void
Tim Peters7c321a82002-07-09 02:57:01 +00001821Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001822{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001823 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001824 if (PyErr_Occurred()) {
1825 PyErr_Print();
1826 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001827#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001828 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001829 OutputDebugString(msg);
1830 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001831#ifdef _DEBUG
1832 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001833#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001834#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001835 abort();
1836}
1837
1838/* Clean up and exit */
1839
Guido van Rossuma110aa61994-08-29 12:50:44 +00001840#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001841#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001842#endif
1843
Collin Winter670e6922007-03-21 02:57:17 +00001844static void (*pyexitfunc)(void) = NULL;
1845/* For the atexit module. */
1846void _Py_PyAtExit(void (*func)(void))
1847{
1848 pyexitfunc = func;
1849}
1850
1851static void
1852call_py_exitfuncs(void)
1853{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001854 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00001855 return;
1856
1857 (*pyexitfunc)();
1858 PyErr_Clear();
1859}
1860
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001861#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001862static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001863static int nexitfuncs = 0;
1864
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001865int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001866{
1867 if (nexitfuncs >= NEXITFUNCS)
1868 return -1;
1869 exitfuncs[nexitfuncs++] = func;
1870 return 0;
1871}
1872
Guido van Rossumcc283f51997-08-05 02:22:03 +00001873static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001874call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001875{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001876 while (nexitfuncs > 0)
1877 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001878
1879 fflush(stdout);
1880 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001881}
1882
1883void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001884Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001885{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001886 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001887
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001888 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001889}
1890
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001891static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001892initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001893{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001894#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001895 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001896#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001897#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001898 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001899#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001900#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001901 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001902#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001903 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001904}
1905
Guido van Rossum7433b121997-02-14 19:45:36 +00001906
1907/*
1908 * The file descriptor fd is considered ``interactive'' if either
1909 * a) isatty(fd) is TRUE, or
1910 * b) the -i flag was given, and the filename associated with
1911 * the descriptor is NULL or "<stdin>" or "???".
1912 */
1913int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001914Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001915{
1916 if (isatty((int)fileno(fp)))
1917 return 1;
1918 if (!Py_InteractiveFlag)
1919 return 0;
1920 return (filename == NULL) ||
1921 (strcmp(filename, "<stdin>") == 0) ||
1922 (strcmp(filename, "???") == 0);
1923}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001924
1925
Tim Petersd08e3822003-04-17 15:24:21 +00001926#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001927#if defined(WIN32) && defined(_MSC_VER)
1928
1929/* Stack checking for Microsoft C */
1930
1931#include <malloc.h>
1932#include <excpt.h>
1933
Fred Drakee8de31c2000-08-31 05:38:39 +00001934/*
1935 * Return non-zero when we run out of memory on the stack; zero otherwise.
1936 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001937int
Fred Drake399739f2000-08-31 05:52:44 +00001938PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001939{
1940 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001941 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001942 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001943 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001944 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00001945 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00001946 EXCEPTION_EXECUTE_HANDLER :
1947 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00001948 int errcode = _resetstkoflw();
1949 if (errcode)
1950 {
1951 Py_FatalError("Could not reset the stack!");
1952 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001953 }
1954 return 1;
1955}
1956
1957#endif /* WIN32 && _MSC_VER */
1958
1959/* Alternate implementations can be added here... */
1960
1961#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001962
1963
1964/* Wrappers around sigaction() or signal(). */
1965
1966PyOS_sighandler_t
1967PyOS_getsig(int sig)
1968{
1969#ifdef HAVE_SIGACTION
1970 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001971 if (sigaction(sig, NULL, &context) == -1)
1972 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001973 return context.sa_handler;
1974#else
1975 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001976/* Special signal handling for the secure CRT in Visual Studio 2005 */
1977#if defined(_MSC_VER) && _MSC_VER >= 1400
1978 switch (sig) {
1979 /* Only these signals are valid */
1980 case SIGINT:
1981 case SIGILL:
1982 case SIGFPE:
1983 case SIGSEGV:
1984 case SIGTERM:
1985 case SIGBREAK:
1986 case SIGABRT:
1987 break;
1988 /* Don't call signal() with other values or it will assert */
1989 default:
1990 return SIG_ERR;
1991 }
1992#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00001993 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001994 if (handler != SIG_ERR)
1995 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00001996 return handler;
1997#endif
1998}
1999
2000PyOS_sighandler_t
2001PyOS_setsig(int sig, PyOS_sighandler_t handler)
2002{
2003#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002004 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002005 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002006 sigemptyset(&context.sa_mask);
2007 context.sa_flags = 0;
2008 if (sigaction(sig, &context, &ocontext) == -1)
2009 return SIG_ERR;
2010 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002011#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002012 PyOS_sighandler_t oldhandler;
2013 oldhandler = signal(sig, handler);
2014#ifdef HAVE_SIGINTERRUPT
2015 siginterrupt(sig, 1);
2016#endif
2017 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002018#endif
2019}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002020
2021/* Deprecated C API functions still provided for binary compatiblity */
2022
2023#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002024PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002025PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2026{
2027 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2028}
2029
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002030#undef PyParser_SimpleParseString
2031PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002032PyParser_SimpleParseString(const char *str, int start)
2033{
2034 return PyParser_SimpleParseStringFlags(str, start, 0);
2035}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002036
2037#undef PyRun_AnyFile
2038PyAPI_FUNC(int)
2039PyRun_AnyFile(FILE *fp, const char *name)
2040{
2041 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2042}
2043
2044#undef PyRun_AnyFileEx
2045PyAPI_FUNC(int)
2046PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2047{
2048 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2049}
2050
2051#undef PyRun_AnyFileFlags
2052PyAPI_FUNC(int)
2053PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2054{
2055 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2056}
2057
2058#undef PyRun_File
2059PyAPI_FUNC(PyObject *)
2060PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2061{
2062 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
2063}
2064
2065#undef PyRun_FileEx
2066PyAPI_FUNC(PyObject *)
2067PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2068{
2069 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
2070}
2071
2072#undef PyRun_FileFlags
2073PyAPI_FUNC(PyObject *)
2074PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2075 PyCompilerFlags *flags)
2076{
2077 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
2078}
2079
2080#undef PyRun_SimpleFile
2081PyAPI_FUNC(int)
2082PyRun_SimpleFile(FILE *f, const char *p)
2083{
2084 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2085}
2086
2087#undef PyRun_SimpleFileEx
2088PyAPI_FUNC(int)
2089PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2090{
2091 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2092}
2093
2094
2095#undef PyRun_String
2096PyAPI_FUNC(PyObject *)
2097PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2098{
2099 return PyRun_StringFlags(str, s, g, l, NULL);
2100}
2101
2102#undef PyRun_SimpleString
2103PyAPI_FUNC(int)
2104PyRun_SimpleString(const char *s)
2105{
2106 return PyRun_SimpleStringFlags(s, NULL);
2107}
2108
2109#undef Py_CompileString
2110PyAPI_FUNC(PyObject *)
2111Py_CompileString(const char *str, const char *p, int s)
2112{
2113 return Py_CompileStringFlags(str, p, s, NULL);
2114}
2115
2116#undef PyRun_InteractiveOne
2117PyAPI_FUNC(int)
2118PyRun_InteractiveOne(FILE *f, const char *p)
2119{
2120 return PyRun_InteractiveOneFlags(f, p, NULL);
2121}
2122
2123#undef PyRun_InteractiveLoop
2124PyAPI_FUNC(int)
2125PyRun_InteractiveLoop(FILE *f, const char *p)
2126{
2127 return PyRun_InteractiveLoopFlags(f, p, NULL);
2128}
2129
2130#ifdef __cplusplus
2131}
2132#endif