blob: 08fa79ee006aee7778c97f12325b046e3a6ce0ed [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000021
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000025
Martin v. Löwis73d538b2003-03-05 15:13:47 +000026#ifdef HAVE_LANGINFO_H
27#include <locale.h>
28#include <langinfo.h>
29#endif
30
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000031#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000032#undef BYTE
33#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000034#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000035#endif
36
Neal Norwitz4281cef2006-03-04 19:58:13 +000037#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000038#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000039#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000040#define PRINT_TOTAL_REFS() fprintf(stderr, \
41 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
42 _Py_GetRefTotal())
43#endif
44
45#ifdef __cplusplus
46extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000047#endif
48
Martin v. Löwis790465f2008-04-05 20:41:37 +000049extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000050
Guido van Rossum82598051997-03-05 00:20:32 +000051extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000052
Guido van Rossumb73cc041993-11-01 16:28:59 +000053/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000054static void initmain(void);
55static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000056static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000057static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000058static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000059 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000060static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000061 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000062static void err_input(perrdetail *);
63static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000064static void call_py_exitfuncs(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000065static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000066extern void _PyUnicode_Init(void);
67extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000068extern int _PyLong_Init(void);
69extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000070
Mark Hammond8d98d2c2003-04-19 15:41:53 +000071#ifdef WITH_THREAD
72extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
73extern void _PyGILState_Fini(void);
74#endif /* WITH_THREAD */
75
Guido van Rossum82598051997-03-05 00:20:32 +000076int Py_DebugFlag; /* Needed by parser.c */
77int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000078int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000079int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000080int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000081int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000082int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000083int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000084int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000085int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000086
Mark Hammonda43fd0c2003-02-19 00:33:33 +000087/* Reference to 'warnings' module, to avoid importing it
Mark Hammondedd07732003-07-15 23:03:55 +000088 on the fly when the import lock may be held. See 683658/771097
Mark Hammonda43fd0c2003-02-19 00:33:33 +000089*/
Mark Hammondedd07732003-07-15 23:03:55 +000090static PyObject *warnings_module = NULL;
91
92/* Returns a borrowed reference to the 'warnings' module, or NULL.
93 If the module is returned, it is guaranteed to have been obtained
94 without acquiring the import lock
95*/
Martin v. Löwisa2c17c52003-08-09 09:47:11 +000096PyObject *PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000097{
98 PyObject *typ, *val, *tb;
99 PyObject *all_modules;
100 /* If we managed to get the module at init time, just use it */
101 if (warnings_module)
102 return warnings_module;
103 /* If it wasn't available at init time, it may be available
104 now in sys.modules (common scenario is frozen apps: import
105 at init time fails, but the frozen init code sets up sys.path
106 correctly, then does an implicit import of warnings for us
107 */
108 /* Save and restore any exceptions */
109 PyErr_Fetch(&typ, &val, &tb);
110
Mark Hammond5f4e8ca2003-07-16 01:54:38 +0000111 all_modules = PySys_GetObject("modules");
Mark Hammondedd07732003-07-15 23:03:55 +0000112 if (all_modules) {
113 warnings_module = PyDict_GetItemString(all_modules, "warnings");
114 /* We keep a ref in the global */
115 Py_XINCREF(warnings_module);
116 }
117 PyErr_Restore(typ, val, tb);
118 return warnings_module;
119}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000122
Thomas Wouters7e474022000-07-16 12:04:32 +0000123/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000124
125int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000126Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000127{
128 return initialized;
129}
130
Guido van Rossum25ce5661997-08-02 03:10:38 +0000131/* Global initializations. Can be undone by Py_Finalize(). Don't
132 call this twice without an intervening Py_Finalize() call. When
133 initializations fail, a fatal error is issued and the function does
134 not return. On return, the first thread and interpreter state have
135 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000136
Guido van Rossum25ce5661997-08-02 03:10:38 +0000137 Locking: you must hold the interpreter lock while calling this.
138 (If the lock has not yet been initialized, that's equivalent to
139 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000140
Guido van Rossum25ce5661997-08-02 03:10:38 +0000141*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000142
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000143static int
144add_flag(int flag, const char *envs)
145{
146 int env = atoi(envs);
147 if (flag < env)
148 flag = env;
149 if (flag < 1)
150 flag = 1;
151 return flag;
152}
153
Guido van Rossuma027efa1997-05-05 20:56:21 +0000154void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000155Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000156{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000157 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000158 PyThreadState *tstate;
Guido van Rossum826d8972007-10-30 18:34:07 +0000159 PyObject *bimod, *sysmod, *pstderr;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000160 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000161#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000162 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000163#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000164 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000165
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000166 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000167 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000168 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000169
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000170#ifdef HAVE_SETLOCALE
171 /* Set up the LC_CTYPE locale, so we can obtain
172 the locale's charset without having to switch
173 locales. */
174 setlocale(LC_CTYPE, "");
175#endif
176
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000177 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000178 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000179 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000180 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000181 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000182 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Christian Heimes790c8232008-01-07 21:14:23 +0000183 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
184 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000185
Guido van Rossuma027efa1997-05-05 20:56:21 +0000186 interp = PyInterpreterState_New();
187 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000188 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000189
Guido van Rossuma027efa1997-05-05 20:56:21 +0000190 tstate = PyThreadState_New(interp);
191 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000192 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000193 (void) PyThreadState_Swap(tstate);
194
Guido van Rossum70d893a2001-08-16 08:21:42 +0000195 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000196
Neal Norwitzb2501f42002-12-31 03:42:13 +0000197 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000198 Py_FatalError("Py_Initialize: can't init frames");
199
Guido van Rossumddefaf32007-01-14 03:31:43 +0000200 if (!_PyLong_Init())
201 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000202
Neal Norwitz6968b052007-02-27 19:02:19 +0000203 if (!PyBytes_Init())
204 Py_FatalError("Py_Initialize: can't init bytes");
205
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000206 _PyFloat_Init();
207
Guido van Rossum25ce5661997-08-02 03:10:38 +0000208 interp->modules = PyDict_New();
209 if (interp->modules == NULL)
210 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000211 interp->modules_reloading = PyDict_New();
212 if (interp->modules_reloading == NULL)
213 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000214
Guido van Rossumc94044c2000-03-10 23:03:54 +0000215 /* Init Unicode implementation; relies on the codec registry */
216 _PyUnicode_Init();
217
Barry Warsawf242aa02000-05-25 23:09:49 +0000218 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000219 if (bimod == NULL)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000220 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000221 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000222 if (interp->builtins == NULL)
223 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000224 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000225
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000226 /* initialize builtin exceptions */
227 _PyExc_Init();
228
Guido van Rossum25ce5661997-08-02 03:10:38 +0000229 sysmod = _PySys_Init();
230 if (sysmod == NULL)
231 Py_FatalError("Py_Initialize: can't initialize sys");
232 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000233 if (interp->sysdict == NULL)
234 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000235 Py_INCREF(interp->sysdict);
236 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000237 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000238 PyDict_SetItemString(interp->sysdict, "modules",
239 interp->modules);
240
Guido van Rossum826d8972007-10-30 18:34:07 +0000241 /* Set up a preliminary stderr printer until we have enough
242 infrastructure for the io module in place. */
243 pstderr = PyFile_NewStdPrinter(fileno(stderr));
244 if (pstderr == NULL)
245 Py_FatalError("Py_Initialize: can't set preliminary stderr");
246 PySys_SetObject("stderr", pstderr);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000247 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000248
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000249 _PyImport_Init();
250
Barry Warsaw035574d1997-08-29 22:07:17 +0000251 /* phase 2 of builtins */
Georg Brandl1a3284e2007-12-02 09:40:06 +0000252 _PyImport_FixupExtension("builtins", "builtins");
Barry Warsaw035574d1997-08-29 22:07:17 +0000253
Just van Rossum52e14d62002-12-30 22:08:05 +0000254 _PyImportHooks_Init();
255
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000256 if (install_sigs)
257 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000258
259 initmain(); /* Module __main__ */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000260 if (initstdio() < 0)
261 Py_FatalError(
262 "Py_Initialize: can't initialize sys standard streams");
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000263 if (!Py_NoSiteFlag)
264 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000265
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000266 /* auto-thread-state API, if available */
267#ifdef WITH_THREAD
268 _PyGILState_Init(interp, tstate);
269#endif /* WITH_THREAD */
270
Mark Hammondedd07732003-07-15 23:03:55 +0000271 warnings_module = PyImport_ImportModule("warnings");
Guido van Rossum98297ee2007-11-06 21:34:58 +0000272 if (!warnings_module) {
Mark Hammondedd07732003-07-15 23:03:55 +0000273 PyErr_Clear();
Guido van Rossum98297ee2007-11-06 21:34:58 +0000274 }
275 else {
276 PyObject *o;
277 char *action[8];
278
279 if (Py_BytesWarningFlag > 1)
280 *action = "error";
281 else if (Py_BytesWarningFlag)
282 *action = "default";
283 else
284 *action = "ignore";
285
286 o = PyObject_CallMethod(warnings_module,
287 "simplefilter", "sO",
288 *action, PyExc_BytesWarning);
289 if (o == NULL)
290 Py_FatalError("Py_Initialize: can't initialize"
291 "warning filter for BytesWarning.");
292 Py_DECREF(o);
293 }
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000294
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000295#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000296 /* On Unix, set the file system encoding according to the
297 user's preference, if the CODESET names a well-known
298 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000299 initialized by other means. Also set the encoding of
300 stdin and stdout if these are terminals. */
301
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000302 codeset = nl_langinfo(CODESET);
303 if (codeset && *codeset) {
304 PyObject *enc = PyCodec_Encoder(codeset);
305 if (enc) {
306 codeset = strdup(codeset);
307 Py_DECREF(enc);
308 } else {
309 codeset = NULL;
310 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000311 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000312 } else
313 codeset = NULL;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000314
315 if (codeset) {
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000316 if (!Py_FileSystemDefaultEncoding)
317 Py_FileSystemDefaultEncoding = codeset;
318 else
319 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000320 }
321#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000322}
323
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000324void
325Py_Initialize(void)
326{
327 Py_InitializeEx(1);
328}
329
330
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000331#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000332extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000333#endif
334
Guido van Rossume8432ac2007-07-09 15:04:50 +0000335/* Flush stdout and stderr */
336
Neal Norwitz2bad9702007-08-27 06:19:22 +0000337static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000338flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000339{
340 PyObject *fout = PySys_GetObject("stdout");
341 PyObject *ferr = PySys_GetObject("stderr");
342 PyObject *tmp;
343
Christian Heimes2be03732007-11-15 02:26:46 +0000344 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000345 tmp = PyObject_CallMethod(fout, "flush", "");
346 if (tmp == NULL)
347 PyErr_Clear();
348 else
349 Py_DECREF(tmp);
350 }
351
Christian Heimes2be03732007-11-15 02:26:46 +0000352 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000353 tmp = PyObject_CallMethod(ferr, "flush", "");
354 if (tmp == NULL)
355 PyErr_Clear();
356 else
357 Py_DECREF(tmp);
358 }
359}
360
Guido van Rossum25ce5661997-08-02 03:10:38 +0000361/* Undo the effect of Py_Initialize().
362
363 Beware: if multiple interpreter and/or thread states exist, these
364 are not wiped out; only the current thread and interpreter state
365 are deleted. But since everything else is deleted, those other
366 interpreter and thread states should no longer be used.
367
368 (XXX We should do better, e.g. wipe out all interpreters and
369 threads.)
370
371 Locking: as above.
372
373*/
374
375void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000376Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000377{
378 PyInterpreterState *interp;
379 PyThreadState *tstate;
380
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000381 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000382 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000383
Tim Peters384fd102001-01-21 03:40:37 +0000384 /* The interpreter is still entirely intact at this point, and the
385 * exit funcs may be relying on that. In particular, if some thread
386 * or exit func is still waiting to do an import, the import machinery
387 * expects Py_IsInitialized() to return true. So don't say the
388 * interpreter is uninitialized until after the exit funcs have run.
389 * Note that Threading.py uses an exit func to do a join on all the
390 * threads created thru it, so this also protects pending imports in
391 * the threads created via Threading.
392 */
Collin Winter670e6922007-03-21 02:57:17 +0000393 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000394 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000395
Guido van Rossume8432ac2007-07-09 15:04:50 +0000396 /* Flush stdout+stderr */
397 flush_std_files();
398
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000399 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000400 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000401 interp = tstate->interp;
402
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000403 /* Disable signal handling */
404 PyOS_FiniInterrupts();
405
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000406 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000407 Py_XDECREF(warnings_module);
408 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000409
Christian Heimes26855632008-01-27 23:50:43 +0000410 /* Clear type lookup cache */
411 PyType_ClearCache();
412
Guido van Rossume13ddc92003-04-17 17:29:22 +0000413 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000414 * before all modules are destroyed.
415 * XXX If a __del__ or weakref callback is triggered here, and tries to
416 * XXX import a module, bad things can happen, because Python no
417 * XXX longer believes it's initialized.
418 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
419 * XXX is easy to provoke that way. I've also seen, e.g.,
420 * XXX Exception exceptions.ImportError: 'No module named sha'
421 * XXX in <function callback at 0x008F5718> ignored
422 * XXX but I'm unclear on exactly how that one happens. In any case,
423 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000424 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000425 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000426#ifdef COUNT_ALLOCS
427 /* With COUNT_ALLOCS, it helps to run GC multiple times:
428 each collection might release some types from the type
429 list, so they become garbage. */
430 while (PyGC_Collect() > 0)
431 /* nothing */;
432#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000433
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000434 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000435 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000436
Guido van Rossume8432ac2007-07-09 15:04:50 +0000437 /* Flush stdout+stderr (again, in case more was printed) */
438 flush_std_files();
439
Guido van Rossume13ddc92003-04-17 17:29:22 +0000440 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000441 * new-style class definitions, for example.
442 * XXX This is disabled because it caused too many problems. If
443 * XXX a __del__ or weakref callback triggers here, Python code has
444 * XXX a hard time running, because even the sys module has been
445 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
446 * XXX One symptom is a sequence of information-free messages
447 * XXX coming from threads (if a __del__ or callback is invoked,
448 * XXX other threads can execute too, and any exception they encounter
449 * XXX triggers a comedy of errors as subsystem after subsystem
450 * XXX fails to find what it *expects* to find in sys to help report
451 * XXX the exception and consequent unexpected failures). I've also
452 * XXX seen segfaults then, after adding print statements to the
453 * XXX Python code getting called.
454 */
455#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000456 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000457#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000458
Guido van Rossum1707aad1997-12-08 23:43:45 +0000459 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
460 _PyImport_Fini();
461
462 /* Debugging stuff */
463#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000464 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000465#endif
466
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000467 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000468
Tim Peters9cf25ce2003-04-17 15:21:01 +0000469#ifdef Py_TRACE_REFS
470 /* Display all objects still alive -- this can invoke arbitrary
471 * __repr__ overrides, so requires a mostly-intact interpreter.
472 * Alas, a lot of stuff may still be alive now that will be cleaned
473 * up later.
474 */
Tim Peters269b2a62003-04-17 19:52:29 +0000475 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000476 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000477#endif /* Py_TRACE_REFS */
478
Guido van Rossumd922fa42003-04-15 14:10:09 +0000479 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000480 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000481
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000482 /* Now we decref the exception classes. After this point nothing
483 can raise an exception. That's okay, because each Fini() method
484 below has been checked to make sure no exceptions are ever
485 raised.
486 */
487
488 _PyExc_Fini();
489
Christian Heimes7d2ff882007-11-30 14:35:04 +0000490 /* Cleanup auto-thread-state */
491#ifdef WITH_THREAD
492 _PyGILState_Fini();
493#endif /* WITH_THREAD */
494
Guido van Rossumd922fa42003-04-15 14:10:09 +0000495 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000496 PyThreadState_Swap(NULL);
497 PyInterpreterState_Delete(interp);
498
Guido van Rossumd922fa42003-04-15 14:10:09 +0000499 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000500 PyMethod_Fini();
501 PyFrame_Fini();
502 PyCFunction_Fini();
503 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000504 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000505 PySet_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000506 PyString_Fini();
Neal Norwitz6968b052007-02-27 19:02:19 +0000507 PyBytes_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000508 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000509 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000510 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000511
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000512 /* Cleanup Unicode implementation */
513 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000514
Christian Heimesc8967002007-11-30 10:18:26 +0000515 /* reset file system default encoding */
516 if (!Py_HasFileSystemDefaultEncoding) {
517 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000518 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000519 }
520
Guido van Rossumcc283f51997-08-05 02:22:03 +0000521 /* XXX Still allocated:
522 - various static ad-hoc pointers to interned strings
523 - int and float free list blocks
524 - whatever various modules and libraries allocate
525 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000526
527 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000528
Tim Peters269b2a62003-04-17 19:52:29 +0000529#ifdef Py_TRACE_REFS
530 /* Display addresses (& refcnts) of all objects still alive.
531 * An address can be used to find the repr of the object, printed
532 * above by _Py_PrintReferences.
533 */
534 if (Py_GETENV("PYTHONDUMPREFS"))
535 _Py_PrintReferenceAddresses(stderr);
536#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000537#ifdef PYMALLOC_DEBUG
538 if (Py_GETENV("PYTHONMALLOCSTATS"))
539 _PyObject_DebugMallocStats();
540#endif
541
Guido van Rossumcc283f51997-08-05 02:22:03 +0000542 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000543}
544
545/* Create and initialize a new interpreter and thread, and return the
546 new thread. This requires that Py_Initialize() has been called
547 first.
548
549 Unsuccessful initialization yields a NULL pointer. Note that *no*
550 exception information is available even in this case -- the
551 exception information is held in the thread, and there is no
552 thread.
553
554 Locking: as above.
555
556*/
557
558PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000559Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560{
561 PyInterpreterState *interp;
562 PyThreadState *tstate, *save_tstate;
563 PyObject *bimod, *sysmod;
564
565 if (!initialized)
566 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
567
568 interp = PyInterpreterState_New();
569 if (interp == NULL)
570 return NULL;
571
572 tstate = PyThreadState_New(interp);
573 if (tstate == NULL) {
574 PyInterpreterState_Delete(interp);
575 return NULL;
576 }
577
578 save_tstate = PyThreadState_Swap(tstate);
579
580 /* XXX The following is lax in error checking */
581
582 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000583 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584
Georg Brandl1a3284e2007-12-02 09:40:06 +0000585 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000586 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000587 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000588 if (interp->builtins == NULL)
589 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000590 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591 }
592 sysmod = _PyImport_FindExtension("sys", "sys");
593 if (bimod != NULL && sysmod != NULL) {
594 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000595 if (interp->sysdict == NULL)
596 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000597 Py_INCREF(interp->sysdict);
598 PySys_SetPath(Py_GetPath());
599 PyDict_SetItemString(interp->sysdict, "modules",
600 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000601 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000602 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000603 if (!Py_NoSiteFlag)
604 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000605 }
606
607 if (!PyErr_Occurred())
608 return tstate;
609
Thomas Wouters89f507f2006-12-13 04:49:30 +0000610handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000611 /* Oops, it didn't work. Undo it all. */
612
613 PyErr_Print();
614 PyThreadState_Clear(tstate);
615 PyThreadState_Swap(save_tstate);
616 PyThreadState_Delete(tstate);
617 PyInterpreterState_Delete(interp);
618
619 return NULL;
620}
621
622/* Delete an interpreter and its last thread. This requires that the
623 given thread state is current, that the thread has no remaining
624 frames, and that it is its interpreter's only remaining thread.
625 It is a fatal error to violate these constraints.
626
627 (Py_Finalize() doesn't have these constraints -- it zaps
628 everything, regardless.)
629
630 Locking: as above.
631
632*/
633
634void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000635Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000636{
637 PyInterpreterState *interp = tstate->interp;
638
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000639 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000640 Py_FatalError("Py_EndInterpreter: thread is not current");
641 if (tstate->frame != NULL)
642 Py_FatalError("Py_EndInterpreter: thread still has a frame");
643 if (tstate != interp->tstate_head || tstate->next != NULL)
644 Py_FatalError("Py_EndInterpreter: not the last thread");
645
646 PyImport_Cleanup();
647 PyInterpreterState_Clear(interp);
648 PyThreadState_Swap(NULL);
649 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000650}
651
Martin v. Löwis790465f2008-04-05 20:41:37 +0000652static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000653
654void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000655Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000656{
657 if (pn && *pn)
658 progname = pn;
659}
660
Martin v. Löwis790465f2008-04-05 20:41:37 +0000661wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000662Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000663{
664 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000665}
666
Martin v. Löwis790465f2008-04-05 20:41:37 +0000667static wchar_t *default_home = NULL;
668static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000669
670void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000671Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000672{
673 default_home = home;
674}
675
Martin v. Löwis790465f2008-04-05 20:41:37 +0000676wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000677Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000678{
Martin v. Löwis790465f2008-04-05 20:41:37 +0000679 wchar_t *home = default_home;
680 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
681 char* chome = Py_GETENV("PYTHONHOME");
682 if (chome) {
683 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
684 if (r != (size_t)-1 && r <= PATH_MAX)
685 home = env_home;
686 }
687
688 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000689 return home;
690}
691
Guido van Rossum6135a871995-01-09 17:53:26 +0000692/* Create __main__ module */
693
694static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000695initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000696{
Guido van Rossum82598051997-03-05 00:20:32 +0000697 PyObject *m, *d;
698 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000699 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000700 Py_FatalError("can't create __main__ module");
701 d = PyModule_GetDict(m);
702 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000703 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000704 if (bimod == NULL ||
705 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000706 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000707 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000708 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000709}
710
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000711/* Import the site module (not into __main__ though) */
712
713static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000714initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000715{
716 PyObject *m, *f;
717 m = PyImport_ImportModule("site");
718 if (m == NULL) {
719 f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +0000720 if (f == NULL || f == Py_None)
721 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000722 if (Py_VerboseFlag) {
723 PyFile_WriteString(
724 "'import site' failed; traceback:\n", f);
725 PyErr_Print();
726 }
727 else {
728 PyFile_WriteString(
729 "'import site' failed; use -v for traceback\n", f);
730 PyErr_Clear();
731 }
732 }
733 else {
734 Py_DECREF(m);
735 }
736}
737
Georg Brandl1a3284e2007-12-02 09:40:06 +0000738/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000739static int
740initstdio(void)
741{
742 PyObject *iomod = NULL, *wrapper;
743 PyObject *bimod = NULL;
744 PyObject *m;
745 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000746 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000747 PyObject * encoding_attr;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000748
749 /* Hack to avoid a nasty recursion issue when Python is invoked
750 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
751 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
752 goto error;
753 }
754 Py_DECREF(m);
755
756 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
757 goto error;
758 }
759 Py_DECREF(m);
760
Georg Brandl1a3284e2007-12-02 09:40:06 +0000761 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000762 goto error;
763 }
764
765 if (!(iomod = PyImport_ImportModule("io"))) {
766 goto error;
767 }
768 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
769 goto error;
770 }
771
Georg Brandl1a3284e2007-12-02 09:40:06 +0000772 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000773 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
774 goto error;
775 }
776
777 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000778 fd = fileno(stdin);
779 /* Under some conditions stdin, stdout and stderr may not be connected
780 * and fileno() may point to an invalid file descriptor. For example
781 * GUI apps don't have valid standard streams by default.
782 */
783 if (fd < 0) {
784#ifdef MS_WINDOWS
785 std = Py_None;
786 Py_INCREF(std);
787#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000788 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000789#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000790 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000791 else {
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000792 if (!(std = PyFile_FromFd(fd, "<stdin>", "r", -1, NULL, NULL,
Christian Heimes58cb1b82007-11-13 02:19:40 +0000793 "\n", 0))) {
794 goto error;
795 }
796 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000797 PySys_SetObject("__stdin__", std);
798 PySys_SetObject("stdin", std);
799 Py_DECREF(std);
800
801 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000802 fd = fileno(stdout);
803 if (fd < 0) {
804#ifdef MS_WINDOWS
805 std = Py_None;
806 Py_INCREF(std);
807#else
808 goto error;
809#endif
810 }
811 else {
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000812 if (!(std = PyFile_FromFd(fd, "<stdout>", "w", -1, NULL, NULL,
Christian Heimes58cb1b82007-11-13 02:19:40 +0000813 "\n", 0))) {
814 goto error;
815 }
816 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000817 PySys_SetObject("__stdout__", std);
818 PySys_SetObject("stdout", std);
819 Py_DECREF(std);
820
Guido van Rossum98297ee2007-11-06 21:34:58 +0000821#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000822 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000823 fd = fileno(stderr);
824 if (fd < 0) {
825#ifdef MS_WINDOWS
826 std = Py_None;
827 Py_INCREF(std);
828#else
829 goto error;
830#endif
831 }
832 else {
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000833 if (!(std = PyFile_FromFd(fd, "<stderr>", "w", -1, NULL, NULL,
Christian Heimes58cb1b82007-11-13 02:19:40 +0000834 "\n", 0))) {
835 goto error;
836 }
837 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000838
839 /* Same as hack above, pre-import stderr's codec to avoid recursion
840 when import.c tries to write to stderr in verbose mode. */
841 encoding_attr = PyObject_GetAttrString(std, "encoding");
842 if (encoding_attr != NULL) {
843 const char * encoding;
844 encoding = PyUnicode_AsString(encoding_attr);
845 if (encoding != NULL) {
846 _PyCodec_Lookup(encoding);
847 }
848 }
849 PyErr_Clear(); /* Not a fatal error if codec isn't available */
850
Christian Heimesdb233082007-11-13 02:34:21 +0000851 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000852 PySys_SetObject("stderr", std);
853 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000854#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000855
Christian Heimes58cb1b82007-11-13 02:19:40 +0000856 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000857 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000858 status = -1;
859 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000860
861 Py_XDECREF(bimod);
862 Py_XDECREF(iomod);
863 return status;
864}
865
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000866/* Parse input from a file and execute it */
867
868int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000869PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000870 PyCompilerFlags *flags)
871{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000872 if (filename == NULL)
873 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000874 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000875 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000876 if (closeit)
877 fclose(fp);
878 return err;
879 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000880 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000881 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000882}
883
884int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000885PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000886{
Guido van Rossum82598051997-03-05 00:20:32 +0000887 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000888 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000889 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000890
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000891 if (flags == NULL) {
892 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000893 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000894 }
Guido van Rossum82598051997-03-05 00:20:32 +0000895 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000896 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000897 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000898 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000899 }
Guido van Rossum82598051997-03-05 00:20:32 +0000900 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000901 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000902 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000903 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000904 }
905 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000906 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000907 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000908 if (ret == E_EOF)
909 return 0;
910 /*
911 if (ret == E_NOMEM)
912 return -1;
913 */
914 }
915}
916
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000917/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000918#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000919 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Guido van Rossum45aecf42006-03-15 04:58:47 +0000920 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000921
Thomas Wouters89f507f2006-12-13 04:49:30 +0000922#if 0
923/* Keep an example of flags with future keyword support. */
924#define PARSER_FLAGS(flags) \
925 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
926 PyPARSE_DONT_IMPLY_DEDENT : 0) \
927 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
928 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
929#endif
930
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000931int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000932PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000933{
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000934 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000935 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +0000936 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000937 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000938 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000939
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000940 if (fp == stdin) {
941 /* Fetch encoding from sys.stdin */
942 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +0000943 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000944 return -1;
945 oenc = PyObject_GetAttrString(v, "encoding");
946 if (!oenc)
947 return -1;
948 enc = PyUnicode_AsString(oenc);
949 }
Guido van Rossum82598051997-03-05 00:20:32 +0000950 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000951 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000952 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000953 if (v == NULL)
954 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000955 else if (PyUnicode_Check(v))
956 ps1 = PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000957 }
Guido van Rossum82598051997-03-05 00:20:32 +0000958 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000959 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000960 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000961 if (w == NULL)
962 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000963 else if (PyUnicode_Check(w))
964 ps2 = PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000965 }
Neal Norwitz9589ee22006-03-04 19:01:22 +0000966 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000967 if (arena == NULL) {
968 Py_XDECREF(v);
969 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000970 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000971 return -1;
972 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000973 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000974 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000975 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +0000976 Py_XDECREF(v);
977 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000978 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000979 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000980 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000981 if (errcode == E_EOF) {
982 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000983 return E_EOF;
984 }
Guido van Rossum82598051997-03-05 00:20:32 +0000985 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000986 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000987 }
Guido van Rossum82598051997-03-05 00:20:32 +0000988 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000989 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000990 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000991 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000992 }
Guido van Rossum82598051997-03-05 00:20:32 +0000993 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000994 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +0000995 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +0000996 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000997 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000998 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000999 return -1;
1000 }
Guido van Rossum82598051997-03-05 00:20:32 +00001001 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001002 return 0;
1003}
1004
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001005/* Check whether a file maybe a pyc file: Look at the extension,
1006 the file type, and, if we may close it, at the first few bytes. */
1007
1008static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001009maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001010{
1011 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1012 return 1;
1013
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001014 /* Only look into the file if we are allowed to close it, since
1015 it then should also be seekable. */
1016 if (closeit) {
1017 /* Read only two bytes of the magic. If the file was opened in
1018 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1019 be read as they are on disk. */
1020 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1021 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001022 /* Mess: In case of -x, the stream is NOT at its start now,
1023 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001024 which makes the current stream position formally undefined,
1025 and a x-platform nightmare.
1026 Unfortunately, we have no direct way to know whether -x
1027 was specified. So we use a terrible hack: if the current
1028 stream position is not 0, we assume -x was specified, and
1029 give up. Bug 132850 on SourceForge spells out the
1030 hopelessness of trying anything else (fseek and ftell
1031 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001032 */
Tim Peters3e876562001-02-11 04:35:39 +00001033 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001034 if (ftell(fp) == 0) {
1035 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001036 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001037 ispyc = 1;
1038 rewind(fp);
1039 }
Tim Peters3e876562001-02-11 04:35:39 +00001040 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001041 }
1042 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001043}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001044
Guido van Rossum0df002c2000-08-27 19:21:52 +00001045int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001046PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001047 PyCompilerFlags *flags)
1048{
Guido van Rossum82598051997-03-05 00:20:32 +00001049 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001050 const char *ext;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001051 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001052
Guido van Rossum82598051997-03-05 00:20:32 +00001053 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001054 if (m == NULL)
1055 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001056 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001057 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001058 PyObject *f;
1059 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001060 if (f == NULL)
1061 return -1;
1062 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1063 Py_DECREF(f);
1064 return -1;
1065 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001066 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001067 Py_DECREF(f);
1068 }
Guido van Rossumfdef2711994-09-14 13:31:04 +00001069 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001070 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001071 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001072 if (closeit)
1073 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001074 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001075 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001076 ret = -1;
1077 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001078 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001079 /* Turn on optimization if a .pyo file is given */
1080 if (strcmp(ext, ".pyo") == 0)
1081 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001082 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001083 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001084 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001085 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001086 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001087 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001088 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001089 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001090 ret = -1;
1091 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001092 }
Guido van Rossum82598051997-03-05 00:20:32 +00001093 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001094 ret = 0;
1095 done:
1096 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1097 PyErr_Clear();
1098 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001099}
1100
1101int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001102PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001103{
Guido van Rossum82598051997-03-05 00:20:32 +00001104 PyObject *m, *d, *v;
1105 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001106 if (m == NULL)
1107 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001108 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001109 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001110 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001111 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001112 return -1;
1113 }
Guido van Rossum82598051997-03-05 00:20:32 +00001114 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001115 return 0;
1116}
1117
Barry Warsaw035574d1997-08-29 22:07:17 +00001118static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001119parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1120 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001121{
1122 long hold;
1123 PyObject *v;
1124
1125 /* old style errors */
1126 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001127 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001128 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001129
1130 /* new style errors. `err' is an instance */
1131
1132 if (! (v = PyObject_GetAttrString(err, "msg")))
1133 goto finally;
1134 *message = v;
1135
1136 if (!(v = PyObject_GetAttrString(err, "filename")))
1137 goto finally;
1138 if (v == Py_None)
1139 *filename = NULL;
Kurt B. Kaiser43b15092008-01-05 04:32:22 +00001140 else if (! (*filename = PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001141 goto finally;
1142
1143 Py_DECREF(v);
1144 if (!(v = PyObject_GetAttrString(err, "lineno")))
1145 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001146 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001147 Py_DECREF(v);
1148 v = NULL;
1149 if (hold < 0 && PyErr_Occurred())
1150 goto finally;
1151 *lineno = (int)hold;
1152
1153 if (!(v = PyObject_GetAttrString(err, "offset")))
1154 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001155 if (v == Py_None) {
1156 *offset = -1;
1157 Py_DECREF(v);
1158 v = NULL;
1159 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001160 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001161 Py_DECREF(v);
1162 v = NULL;
1163 if (hold < 0 && PyErr_Occurred())
1164 goto finally;
1165 *offset = (int)hold;
1166 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001167
1168 if (!(v = PyObject_GetAttrString(err, "text")))
1169 goto finally;
1170 if (v == Py_None)
1171 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001172 else if (!PyUnicode_Check(v) ||
1173 !(*text = PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001174 goto finally;
1175 Py_DECREF(v);
1176 return 1;
1177
1178finally:
1179 Py_XDECREF(v);
1180 return 0;
1181}
1182
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001183void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001184PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001185{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001186 PyErr_PrintEx(1);
1187}
1188
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001189static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001190print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001191{
1192 char *nl;
1193 if (offset >= 0) {
1194 if (offset > 0 && offset == (int)strlen(text))
1195 offset--;
1196 for (;;) {
1197 nl = strchr(text, '\n');
1198 if (nl == NULL || nl-text >= offset)
1199 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001200 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001201 text = nl+1;
1202 }
1203 while (*text == ' ' || *text == '\t') {
1204 text++;
1205 offset--;
1206 }
1207 }
1208 PyFile_WriteString(" ", f);
1209 PyFile_WriteString(text, f);
1210 if (*text == '\0' || text[strlen(text)-1] != '\n')
1211 PyFile_WriteString("\n", f);
1212 if (offset == -1)
1213 return;
1214 PyFile_WriteString(" ", f);
1215 offset--;
1216 while (offset > 0) {
1217 PyFile_WriteString(" ", f);
1218 offset--;
1219 }
1220 PyFile_WriteString("^\n", f);
1221}
1222
Guido van Rossum66e8e862001-03-23 17:54:43 +00001223static void
1224handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001225{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001226 PyObject *exception, *value, *tb;
1227 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001228
Guido van Rossumd8faa362007-04-27 19:54:29 +00001229 if (Py_InspectFlag)
1230 /* Don't exit if -i flag was given. This flag is set to 0
1231 * when entering interactive mode for inspecting. */
1232 return;
1233
Guido van Rossum66e8e862001-03-23 17:54:43 +00001234 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001235 fflush(stdout);
1236 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001237 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001238 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001239 /* The error code should be in the `code' attribute. */
1240 PyObject *code = PyObject_GetAttrString(value, "code");
1241 if (code) {
1242 Py_DECREF(value);
1243 value = code;
1244 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001245 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001246 }
1247 /* If we failed to dig out the 'code' attribute,
1248 just let the else clause below print the error. */
1249 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001250 if (PyLong_Check(value))
1251 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001252 else {
1253 PyObject_Print(value, stderr, Py_PRINT_RAW);
1254 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001255 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001256 }
Tim Peterscf615b52003-04-19 18:47:02 +00001257 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001258 /* Restore and clear the exception info, in order to properly decref
1259 * the exception, value, and traceback. If we just exit instead,
1260 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1261 * some finalizers from running.
1262 */
Tim Peterscf615b52003-04-19 18:47:02 +00001263 PyErr_Restore(exception, value, tb);
1264 PyErr_Clear();
1265 Py_Exit(exitcode);
1266 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001267}
1268
1269void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001270PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001271{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001272 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001273
1274 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1275 handle_system_exit();
1276 }
Guido van Rossum82598051997-03-05 00:20:32 +00001277 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001278 if (exception == NULL)
1279 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001280 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001281 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001282 return;
Guido van Rossum9d785502006-03-07 18:31:44 +00001283 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001284 if (set_sys_last_vars) {
1285 PySys_SetObject("last_type", exception);
1286 PySys_SetObject("last_value", v);
Guido van Rossumc5724de2007-10-10 21:38:59 +00001287 PySys_SetObject("last_traceback", tb ? tb : Py_None);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001288 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001289 hook = PySys_GetObject("excepthook");
1290 if (hook) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001291 PyObject *args = PyTuple_Pack(3,
Guido van Rossum9d785502006-03-07 18:31:44 +00001292 exception, v, tb ? tb : Py_None);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001293 PyObject *result = PyEval_CallObject(hook, args);
1294 if (result == NULL) {
1295 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001296 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1297 handle_system_exit();
1298 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001299 PyErr_Fetch(&exception2, &v2, &tb2);
1300 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001301 /* It should not be possible for exception2 or v2
1302 to be NULL. However PyErr_Display() can't
1303 tolerate NULLs, so just be safe. */
1304 if (exception2 == NULL) {
1305 exception2 = Py_None;
1306 Py_INCREF(exception2);
1307 }
1308 if (v2 == NULL) {
1309 v2 = Py_None;
1310 Py_INCREF(v2);
1311 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001312 fflush(stdout);
1313 PySys_WriteStderr("Error in sys.excepthook:\n");
1314 PyErr_Display(exception2, v2, tb2);
1315 PySys_WriteStderr("\nOriginal exception was:\n");
1316 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001317 Py_DECREF(exception2);
1318 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001319 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001320 }
1321 Py_XDECREF(result);
1322 Py_XDECREF(args);
1323 } else {
1324 PySys_WriteStderr("sys.excepthook is missing\n");
1325 PyErr_Display(exception, v, tb);
1326 }
1327 Py_XDECREF(exception);
1328 Py_XDECREF(v);
1329 Py_XDECREF(tb);
1330}
1331
Thomas Wouters477c8d52006-05-27 19:21:47 +00001332void
1333PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001334{
1335 int err = 0;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001336 PyObject *f = PySys_GetObject("stderr");
Armin Rigo5d2c6832004-03-22 20:16:58 +00001337 Py_INCREF(value);
Christian Heimes2be03732007-11-15 02:26:46 +00001338 if (f == Py_None) {
1339 /* pass */
1340 }
1341 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001342 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001343 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001344 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001345 else {
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001346 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001347 if (tb && tb != Py_None)
1348 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001349 if (err == 0 &&
Armin Rigo5d2c6832004-03-22 20:16:58 +00001350 PyObject_HasAttrString(value, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001351 {
Guido van Rossum82598051997-03-05 00:20:32 +00001352 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001353 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001354 int lineno, offset;
Armin Rigo5d2c6832004-03-22 20:16:58 +00001355 if (!parse_syntax_error(value, &message, &filename,
Barry Warsaw035574d1997-08-29 22:07:17 +00001356 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001357 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001358 else {
1359 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001360 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001361 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001362 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001363 else
Guido van Rossum82598051997-03-05 00:20:32 +00001364 PyFile_WriteString(filename, f);
1365 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001366 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001367 PyFile_WriteString(buf, f);
1368 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001369 if (text != NULL)
1370 print_error_text(f, offset, text);
Armin Rigo5d2c6832004-03-22 20:16:58 +00001371 Py_DECREF(value);
1372 value = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001373 /* Can't be bothered to check all those
1374 PyFile_WriteString() calls */
1375 if (PyErr_Occurred())
1376 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001377 }
1378 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001379 if (err) {
1380 /* Don't do anything else */
1381 }
Brett Cannonbf364092006-03-01 04:25:17 +00001382 else if (PyExceptionClass_Check(exception)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001383 PyObject* moduleName;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001384 char* className = PyExceptionClass_Name(exception);
1385 if (className != NULL) {
1386 char *dot = strrchr(className, '.');
1387 if (dot != NULL)
1388 className = dot+1;
1389 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001390
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001391 moduleName = PyObject_GetAttrString(exception, "__module__");
Guido van Rossumc5724de2007-10-10 21:38:59 +00001392 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1393 {
1394 Py_DECREF(moduleName);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001395 err = PyFile_WriteString("<unknown>", f);
Guido van Rossumc5724de2007-10-10 21:38:59 +00001396 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001397 else {
Guido van Rossumc5724de2007-10-10 21:38:59 +00001398 char* modstr = PyUnicode_AsString(moduleName);
Georg Brandl1a3284e2007-12-02 09:40:06 +00001399 if (modstr && strcmp(modstr, "builtins"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001400 {
1401 err = PyFile_WriteString(modstr, f);
1402 err += PyFile_WriteString(".", f);
1403 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001404 Py_DECREF(moduleName);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001405 }
1406 if (err == 0) {
1407 if (className == NULL)
1408 err = PyFile_WriteString("<unknown>", f);
1409 else
Brett Cannonbf364092006-03-01 04:25:17 +00001410 err = PyFile_WriteString(className, f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001411 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001412 }
1413 else
1414 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
Brett Cannon2e63b732006-03-02 18:34:57 +00001415 if (err == 0 && (value != Py_None)) {
Thomas Heller519a0422007-11-15 20:48:54 +00001416 PyObject *s = PyObject_Str(value);
Brett Cannon2e63b732006-03-02 18:34:57 +00001417 /* only print colon if the str() of the
1418 object is not the empty string
1419 */
1420 if (s == NULL)
1421 err = -1;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001422 else if (!PyUnicode_Check(s) ||
1423 PyUnicode_GetSize(s) != 0)
Brett Cannon2e63b732006-03-02 18:34:57 +00001424 err = PyFile_WriteString(": ", f);
1425 if (err == 0)
1426 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1427 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001428 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001429 /* try to write a newline in any case */
1430 err += PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001431 }
Armin Rigo5d2c6832004-03-22 20:16:58 +00001432 Py_DECREF(value);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001433 /* If an error happened here, don't show it.
1434 XXX This is wrong, but too many callers rely on this behavior. */
1435 if (err != 0)
1436 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001437}
1438
Guido van Rossum82598051997-03-05 00:20:32 +00001439PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001440PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001441 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001442{
Neal Norwitze92fba02006-03-04 18:52:26 +00001443 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001444 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001445 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001446 if (arena == NULL)
1447 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001448
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001449 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001450 if (mod != NULL)
1451 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001452 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001453 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001454}
1455
1456PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001457PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001458 PyObject *locals, int closeit, PyCompilerFlags *flags)
1459{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001460 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001461 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001462 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001463 if (arena == NULL)
1464 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001465
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001466 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001467 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001468 if (closeit)
1469 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001470 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001471 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001472 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001473 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001474 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001475 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001476 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001477}
1478
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001479static void
1480flush_io(void)
1481{
1482 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001483 PyObject *type, *value, *traceback;
1484
1485 /* Save the current exception */
1486 PyErr_Fetch(&type, &value, &traceback);
1487
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001488 f = PySys_GetObject("stderr");
1489 if (f != NULL) {
1490 r = PyObject_CallMethod(f, "flush", "");
1491 if (r)
1492 Py_DECREF(r);
1493 else
1494 PyErr_Clear();
1495 }
1496 f = PySys_GetObject("stdout");
1497 if (f != NULL) {
1498 r = PyObject_CallMethod(f, "flush", "");
1499 if (r)
1500 Py_DECREF(r);
1501 else
1502 PyErr_Clear();
1503 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001504
1505 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001506}
1507
Guido van Rossum82598051997-03-05 00:20:32 +00001508static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001509run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001510 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001511{
Guido van Rossum82598051997-03-05 00:20:32 +00001512 PyCodeObject *co;
1513 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001514 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001515 if (co == NULL)
1516 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001517 v = PyEval_EvalCode(co, globals, locals);
1518 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001519 return v;
1520}
1521
Guido van Rossum82598051997-03-05 00:20:32 +00001522static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001523run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001524 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001525{
Guido van Rossum82598051997-03-05 00:20:32 +00001526 PyCodeObject *co;
1527 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001528 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001529 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001530
Guido van Rossum82598051997-03-05 00:20:32 +00001531 magic = PyMarshal_ReadLongFromFile(fp);
1532 if (magic != PyImport_GetMagicNumber()) {
1533 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001534 "Bad magic number in .pyc file");
1535 return NULL;
1536 }
Guido van Rossum82598051997-03-05 00:20:32 +00001537 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001538 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001539 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001540 if (v == NULL || !PyCode_Check(v)) {
1541 Py_XDECREF(v);
1542 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001543 "Bad code object in .pyc file");
1544 return NULL;
1545 }
Guido van Rossum82598051997-03-05 00:20:32 +00001546 co = (PyCodeObject *)v;
1547 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001548 if (v && flags)
1549 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001550 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001551 return v;
1552}
1553
Guido van Rossum82598051997-03-05 00:20:32 +00001554PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001555Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001556 PyCompilerFlags *flags)
1557{
Guido van Rossum82598051997-03-05 00:20:32 +00001558 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001559 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001560 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001561 if (arena == NULL)
1562 return NULL;
1563
1564 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001565 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001566 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001567 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001568 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001569 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001570 PyObject *result = PyAST_mod2obj(mod);
1571 PyArena_Free(arena);
1572 return result;
1573 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001574 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001575 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001576 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001577}
1578
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001579struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001580Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001581{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001582 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001583 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001584 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001585 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001586 if (arena == NULL)
1587 return NULL;
1588
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001589 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001590 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001591 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001592 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001593 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001594 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001595 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001596 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001597 return st;
1598}
1599
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001600/* Preferred access to parser is through AST. */
1601mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001602PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001603 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001604{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001605 mod_ty mod;
1606 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001607 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001608
1609 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001610 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001611 &iflags);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001612 if (n) {
Christian Heimes4d6ec852008-03-26 22:34:47 +00001613 if (flags) {
1614 flags->cf_flags |= iflags & PyCF_MASK;
1615 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001616 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001617 PyNode_Free(n);
1618 return mod;
1619 }
1620 else {
1621 err_input(&err);
1622 return NULL;
1623 }
1624}
1625
1626mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001627PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1628 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001629 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001630 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001631{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001632 mod_ty mod;
1633 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001634 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001635
Christian Heimes4d6ec852008-03-26 22:34:47 +00001636 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001637 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001638 start, ps1, ps2, &err, &iflags);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001639 if (n) {
Christian Heimes4d6ec852008-03-26 22:34:47 +00001640 if (flags) {
1641 flags->cf_flags |= iflags & PyCF_MASK;
1642 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001643 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001644 PyNode_Free(n);
1645 return mod;
1646 }
1647 else {
1648 err_input(&err);
1649 if (errcode)
1650 *errcode = err.error;
1651 return NULL;
1652 }
1653}
1654
Guido van Rossuma110aa61994-08-29 12:50:44 +00001655/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001656
Guido van Rossuma110aa61994-08-29 12:50:44 +00001657node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001658PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001659{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001660 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001661 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1662 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001663 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001664 if (n == NULL)
1665 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001666
Guido van Rossuma110aa61994-08-29 12:50:44 +00001667 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001668}
1669
Guido van Rossuma110aa61994-08-29 12:50:44 +00001670/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001671
Guido van Rossuma110aa61994-08-29 12:50:44 +00001672node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001673PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001674{
Tim Petersfe2127d2001-07-16 05:37:24 +00001675 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001676 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1677 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001678 if (n == NULL)
1679 err_input(&err);
1680 return n;
1681}
1682
1683node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001684PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001685 int start, int flags)
1686{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001687 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001688 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1689 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001690 if (n == NULL)
1691 err_input(&err);
1692 return n;
1693}
1694
1695node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001696PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001697{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001698 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001699}
1700
Guido van Rossum66ebd912003-04-17 16:02:26 +00001701/* May want to move a more generalized form of this to parsetok.c or
1702 even parser modules. */
1703
1704void
1705PyParser_SetError(perrdetail *err)
1706{
1707 err_input(err);
1708}
1709
Guido van Rossuma110aa61994-08-29 12:50:44 +00001710/* Set the error appropriate to the given input error code (see errcode.h) */
1711
1712static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001713err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001714{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001715 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001716 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001717 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001718 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001719 switch (err->error) {
1720 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001721 errtype = PyExc_IndentationError;
1722 if (err->expected == INDENT)
1723 msg = "expected an indented block";
1724 else if (err->token == INDENT)
1725 msg = "unexpected indent";
1726 else if (err->token == DEDENT)
1727 msg = "unexpected unindent";
1728 else {
1729 errtype = PyExc_SyntaxError;
1730 msg = "invalid syntax";
1731 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001732 break;
1733 case E_TOKEN:
1734 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001735 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001736 case E_EOFS:
1737 msg = "EOF while scanning triple-quoted string";
1738 break;
1739 case E_EOLS:
1740 msg = "EOL while scanning single-quoted string";
1741 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001742 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001743 if (!PyErr_Occurred())
1744 PyErr_SetNone(PyExc_KeyboardInterrupt);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001745 return;
1746 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001747 PyErr_NoMemory();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001748 return;
1749 case E_EOF:
1750 msg = "unexpected EOF while parsing";
1751 break;
Fred Drake85f36392000-07-11 17:53:00 +00001752 case E_TABSPACE:
1753 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001754 msg = "inconsistent use of tabs and spaces in indentation";
1755 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001756 case E_OVERFLOW:
1757 msg = "expression too long";
1758 break;
Fred Drake85f36392000-07-11 17:53:00 +00001759 case E_DEDENT:
1760 errtype = PyExc_IndentationError;
1761 msg = "unindent does not match any outer indentation level";
1762 break;
1763 case E_TOODEEP:
1764 errtype = PyExc_IndentationError;
1765 msg = "too many levels of indentation";
1766 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001767 case E_DECODE: {
1768 PyObject *type, *value, *tb;
1769 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001770 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001771 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001772 if (u != NULL) {
Guido van Rossumc5724de2007-10-10 21:38:59 +00001773 msg = PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001774 }
1775 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001776 if (msg == NULL)
1777 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001778 Py_XDECREF(type);
1779 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001780 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001781 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001782 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001783 case E_LINECONT:
1784 msg = "unexpected character after line continuation character";
1785 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001786
1787 case E_IDENTIFIER:
1788 msg = "invalid character in identifier";
1789 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001790 default:
1791 fprintf(stderr, "error=%d\n", err->error);
1792 msg = "unknown parsing error";
1793 break;
1794 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001795 /* err->text may not be UTF-8 in case of decoding errors.
1796 Explicitly convert to an object. */
1797 if (!err->text) {
1798 errtext = Py_None;
1799 Py_INCREF(Py_None);
1800 } else {
1801 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1802 "replace");
1803 }
1804 v = Py_BuildValue("(ziiN)", err->filename,
1805 err->lineno, err->offset, errtext);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001806 if (err->text != NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001807 PyObject_FREE(err->text);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001808 err->text = NULL;
1809 }
1810 w = NULL;
1811 if (v != NULL)
1812 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001813 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001814 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001815 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001816 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001817}
1818
1819/* Print fatal error message and abort */
1820
1821void
Tim Peters7c321a82002-07-09 02:57:01 +00001822Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001823{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001824 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001825 if (PyErr_Occurred()) {
1826 PyErr_Print();
1827 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001828#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001829 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001830 OutputDebugString(msg);
1831 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001832#ifdef _DEBUG
1833 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001834#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001835#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001836 abort();
1837}
1838
1839/* Clean up and exit */
1840
Guido van Rossuma110aa61994-08-29 12:50:44 +00001841#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001842#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001843#endif
1844
Collin Winter670e6922007-03-21 02:57:17 +00001845static void (*pyexitfunc)(void) = NULL;
1846/* For the atexit module. */
1847void _Py_PyAtExit(void (*func)(void))
1848{
1849 pyexitfunc = func;
1850}
1851
1852static void
1853call_py_exitfuncs(void)
1854{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001855 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00001856 return;
1857
1858 (*pyexitfunc)();
1859 PyErr_Clear();
1860}
1861
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001862#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001863static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001864static int nexitfuncs = 0;
1865
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001866int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001867{
1868 if (nexitfuncs >= NEXITFUNCS)
1869 return -1;
1870 exitfuncs[nexitfuncs++] = func;
1871 return 0;
1872}
1873
Guido van Rossumcc283f51997-08-05 02:22:03 +00001874static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001875call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001876{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001877 while (nexitfuncs > 0)
1878 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001879
1880 fflush(stdout);
1881 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001882}
1883
1884void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001885Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001886{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001887 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001888
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001889 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001890}
1891
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001892static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001893initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001894{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001895#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001896 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001897#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001898#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001899 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001900#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001901#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001902 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001903#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001904 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001905}
1906
Guido van Rossum7433b121997-02-14 19:45:36 +00001907
1908/*
1909 * The file descriptor fd is considered ``interactive'' if either
1910 * a) isatty(fd) is TRUE, or
1911 * b) the -i flag was given, and the filename associated with
1912 * the descriptor is NULL or "<stdin>" or "???".
1913 */
1914int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001915Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001916{
1917 if (isatty((int)fileno(fp)))
1918 return 1;
1919 if (!Py_InteractiveFlag)
1920 return 0;
1921 return (filename == NULL) ||
1922 (strcmp(filename, "<stdin>") == 0) ||
1923 (strcmp(filename, "???") == 0);
1924}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001925
1926
Tim Petersd08e3822003-04-17 15:24:21 +00001927#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001928#if defined(WIN32) && defined(_MSC_VER)
1929
1930/* Stack checking for Microsoft C */
1931
1932#include <malloc.h>
1933#include <excpt.h>
1934
Fred Drakee8de31c2000-08-31 05:38:39 +00001935/*
1936 * Return non-zero when we run out of memory on the stack; zero otherwise.
1937 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001938int
Fred Drake399739f2000-08-31 05:52:44 +00001939PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001940{
1941 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001942 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001943 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001944 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001945 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00001946 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00001947 EXCEPTION_EXECUTE_HANDLER :
1948 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00001949 int errcode = _resetstkoflw();
1950 if (errcode)
1951 {
1952 Py_FatalError("Could not reset the stack!");
1953 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001954 }
1955 return 1;
1956}
1957
1958#endif /* WIN32 && _MSC_VER */
1959
1960/* Alternate implementations can be added here... */
1961
1962#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001963
1964
1965/* Wrappers around sigaction() or signal(). */
1966
1967PyOS_sighandler_t
1968PyOS_getsig(int sig)
1969{
1970#ifdef HAVE_SIGACTION
1971 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001972 if (sigaction(sig, NULL, &context) == -1)
1973 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001974 return context.sa_handler;
1975#else
1976 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001977/* Special signal handling for the secure CRT in Visual Studio 2005 */
1978#if defined(_MSC_VER) && _MSC_VER >= 1400
1979 switch (sig) {
1980 /* Only these signals are valid */
1981 case SIGINT:
1982 case SIGILL:
1983 case SIGFPE:
1984 case SIGSEGV:
1985 case SIGTERM:
1986 case SIGBREAK:
1987 case SIGABRT:
1988 break;
1989 /* Don't call signal() with other values or it will assert */
1990 default:
1991 return SIG_ERR;
1992 }
1993#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00001994 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001995 if (handler != SIG_ERR)
1996 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00001997 return handler;
1998#endif
1999}
2000
2001PyOS_sighandler_t
2002PyOS_setsig(int sig, PyOS_sighandler_t handler)
2003{
2004#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002005 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002006 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002007 sigemptyset(&context.sa_mask);
2008 context.sa_flags = 0;
2009 if (sigaction(sig, &context, &ocontext) == -1)
2010 return SIG_ERR;
2011 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002012#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002013 PyOS_sighandler_t oldhandler;
2014 oldhandler = signal(sig, handler);
2015#ifdef HAVE_SIGINTERRUPT
2016 siginterrupt(sig, 1);
2017#endif
2018 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002019#endif
2020}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002021
2022/* Deprecated C API functions still provided for binary compatiblity */
2023
2024#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002025PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002026PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2027{
2028 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2029}
2030
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002031#undef PyParser_SimpleParseString
2032PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002033PyParser_SimpleParseString(const char *str, int start)
2034{
2035 return PyParser_SimpleParseStringFlags(str, start, 0);
2036}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002037
2038#undef PyRun_AnyFile
2039PyAPI_FUNC(int)
2040PyRun_AnyFile(FILE *fp, const char *name)
2041{
2042 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2043}
2044
2045#undef PyRun_AnyFileEx
2046PyAPI_FUNC(int)
2047PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2048{
2049 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2050}
2051
2052#undef PyRun_AnyFileFlags
2053PyAPI_FUNC(int)
2054PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2055{
2056 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2057}
2058
2059#undef PyRun_File
2060PyAPI_FUNC(PyObject *)
2061PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2062{
2063 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
2064}
2065
2066#undef PyRun_FileEx
2067PyAPI_FUNC(PyObject *)
2068PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2069{
2070 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
2071}
2072
2073#undef PyRun_FileFlags
2074PyAPI_FUNC(PyObject *)
2075PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2076 PyCompilerFlags *flags)
2077{
2078 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
2079}
2080
2081#undef PyRun_SimpleFile
2082PyAPI_FUNC(int)
2083PyRun_SimpleFile(FILE *f, const char *p)
2084{
2085 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2086}
2087
2088#undef PyRun_SimpleFileEx
2089PyAPI_FUNC(int)
2090PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2091{
2092 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2093}
2094
2095
2096#undef PyRun_String
2097PyAPI_FUNC(PyObject *)
2098PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2099{
2100 return PyRun_StringFlags(str, s, g, l, NULL);
2101}
2102
2103#undef PyRun_SimpleString
2104PyAPI_FUNC(int)
2105PyRun_SimpleString(const char *s)
2106{
2107 return PyRun_SimpleStringFlags(s, NULL);
2108}
2109
2110#undef Py_CompileString
2111PyAPI_FUNC(PyObject *)
2112Py_CompileString(const char *str, const char *p, int s)
2113{
2114 return Py_CompileStringFlags(str, p, s, NULL);
2115}
2116
2117#undef PyRun_InteractiveOne
2118PyAPI_FUNC(int)
2119PyRun_InteractiveOne(FILE *f, const char *p)
2120{
2121 return PyRun_InteractiveOneFlags(f, p, NULL);
2122}
2123
2124#undef PyRun_InteractiveLoop
2125PyAPI_FUNC(int)
2126PyRun_InteractiveLoop(FILE *f, const char *p)
2127{
2128 return PyRun_InteractiveLoopFlags(f, p, NULL);
2129}
2130
2131#ifdef __cplusplus
2132}
2133#endif