blob: 3207fb8b8174465a02e5c482505690f3dd3ed42b [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"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000020
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000023#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000024
Martin v. Löwis73d538b2003-03-05 15:13:47 +000025#ifdef HAVE_LANGINFO_H
26#include <locale.h>
27#include <langinfo.h>
28#endif
29
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000030#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000031#undef BYTE
32#include "windows.h"
33#endif
34
Neal Norwitz4281cef2006-03-04 19:58:13 +000035#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000036#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000037#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000038#define PRINT_TOTAL_REFS() fprintf(stderr, \
39 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
40 _Py_GetRefTotal())
41#endif
42
43#ifdef __cplusplus
44extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000045#endif
46
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000047extern char *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000048
Guido van Rossum82598051997-03-05 00:20:32 +000049extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000050
Guido van Rossumb73cc041993-11-01 16:28:59 +000051/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000052static void initmain(void);
53static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000054static int initstdio(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000055static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000056 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000057static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000058 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000059static void err_input(perrdetail *);
60static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000061static void call_py_exitfuncs(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000062static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000063extern void _PyUnicode_Init(void);
64extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000065extern int _PyLong_Init(void);
66extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000067
Mark Hammond8d98d2c2003-04-19 15:41:53 +000068#ifdef WITH_THREAD
69extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
70extern void _PyGILState_Fini(void);
71#endif /* WITH_THREAD */
72
Guido van Rossum82598051997-03-05 00:20:32 +000073int Py_DebugFlag; /* Needed by parser.c */
74int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000075int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000076int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000077int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000078int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000079int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000080int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000081int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000082int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000083
Mark Hammonda43fd0c2003-02-19 00:33:33 +000084/* Reference to 'warnings' module, to avoid importing it
Mark Hammondedd07732003-07-15 23:03:55 +000085 on the fly when the import lock may be held. See 683658/771097
Mark Hammonda43fd0c2003-02-19 00:33:33 +000086*/
Mark Hammondedd07732003-07-15 23:03:55 +000087static PyObject *warnings_module = NULL;
88
89/* Returns a borrowed reference to the 'warnings' module, or NULL.
90 If the module is returned, it is guaranteed to have been obtained
91 without acquiring the import lock
92*/
Martin v. Löwisa2c17c52003-08-09 09:47:11 +000093PyObject *PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000094{
95 PyObject *typ, *val, *tb;
96 PyObject *all_modules;
97 /* If we managed to get the module at init time, just use it */
98 if (warnings_module)
99 return warnings_module;
100 /* If it wasn't available at init time, it may be available
101 now in sys.modules (common scenario is frozen apps: import
102 at init time fails, but the frozen init code sets up sys.path
103 correctly, then does an implicit import of warnings for us
104 */
105 /* Save and restore any exceptions */
106 PyErr_Fetch(&typ, &val, &tb);
107
Mark Hammond5f4e8ca2003-07-16 01:54:38 +0000108 all_modules = PySys_GetObject("modules");
Mark Hammondedd07732003-07-15 23:03:55 +0000109 if (all_modules) {
110 warnings_module = PyDict_GetItemString(all_modules, "warnings");
111 /* We keep a ref in the global */
112 Py_XINCREF(warnings_module);
113 }
114 PyErr_Restore(typ, val, tb);
115 return warnings_module;
116}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000117
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000119
Thomas Wouters7e474022000-07-16 12:04:32 +0000120/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000121
122int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000123Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000124{
125 return initialized;
126}
127
Guido van Rossum25ce5661997-08-02 03:10:38 +0000128/* Global initializations. Can be undone by Py_Finalize(). Don't
129 call this twice without an intervening Py_Finalize() call. When
130 initializations fail, a fatal error is issued and the function does
131 not return. On return, the first thread and interpreter state have
132 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000133
Guido van Rossum25ce5661997-08-02 03:10:38 +0000134 Locking: you must hold the interpreter lock while calling this.
135 (If the lock has not yet been initialized, that's equivalent to
136 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000137
Guido van Rossum25ce5661997-08-02 03:10:38 +0000138*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000139
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000140static int
141add_flag(int flag, const char *envs)
142{
143 int env = atoi(envs);
144 if (flag < env)
145 flag = env;
146 if (flag < 1)
147 flag = 1;
148 return flag;
149}
150
Guido van Rossuma027efa1997-05-05 20:56:21 +0000151void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000152Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000153{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000154 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000155 PyThreadState *tstate;
Guido van Rossum826d8972007-10-30 18:34:07 +0000156 PyObject *bimod, *sysmod, *pstderr;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000157 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000158#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000159 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000160#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000161 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000162
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000163 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000164 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000165 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000166
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000167#ifdef HAVE_SETLOCALE
168 /* Set up the LC_CTYPE locale, so we can obtain
169 the locale's charset without having to switch
170 locales. */
171 setlocale(LC_CTYPE, "");
172#endif
173
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000174 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000175 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000176 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000177 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000178 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000179 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Christian Heimes790c8232008-01-07 21:14:23 +0000180 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
181 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000182
Guido van Rossuma027efa1997-05-05 20:56:21 +0000183 interp = PyInterpreterState_New();
184 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000185 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000186
Guido van Rossuma027efa1997-05-05 20:56:21 +0000187 tstate = PyThreadState_New(interp);
188 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000189 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000190 (void) PyThreadState_Swap(tstate);
191
Guido van Rossum70d893a2001-08-16 08:21:42 +0000192 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000193
Neal Norwitzb2501f42002-12-31 03:42:13 +0000194 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000195 Py_FatalError("Py_Initialize: can't init frames");
196
Guido van Rossumddefaf32007-01-14 03:31:43 +0000197 if (!_PyLong_Init())
198 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000199
Neal Norwitz6968b052007-02-27 19:02:19 +0000200 if (!PyBytes_Init())
201 Py_FatalError("Py_Initialize: can't init bytes");
202
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000203 _PyFloat_Init();
204
Guido van Rossum25ce5661997-08-02 03:10:38 +0000205 interp->modules = PyDict_New();
206 if (interp->modules == NULL)
207 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208 interp->modules_reloading = PyDict_New();
209 if (interp->modules_reloading == NULL)
210 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000211
Guido van Rossumc94044c2000-03-10 23:03:54 +0000212 /* Init Unicode implementation; relies on the codec registry */
213 _PyUnicode_Init();
214
Barry Warsawf242aa02000-05-25 23:09:49 +0000215 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000216 if (bimod == NULL)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000217 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000218 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000219 if (interp->builtins == NULL)
220 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000221 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000222
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000223 /* initialize builtin exceptions */
224 _PyExc_Init();
225
Guido van Rossum25ce5661997-08-02 03:10:38 +0000226 sysmod = _PySys_Init();
227 if (sysmod == NULL)
228 Py_FatalError("Py_Initialize: can't initialize sys");
229 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000230 if (interp->sysdict == NULL)
231 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000232 Py_INCREF(interp->sysdict);
233 _PyImport_FixupExtension("sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000234 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000235 PyDict_SetItemString(interp->sysdict, "modules",
236 interp->modules);
237
Guido van Rossum826d8972007-10-30 18:34:07 +0000238 /* Set up a preliminary stderr printer until we have enough
239 infrastructure for the io module in place. */
240 pstderr = PyFile_NewStdPrinter(fileno(stderr));
241 if (pstderr == NULL)
242 Py_FatalError("Py_Initialize: can't set preliminary stderr");
243 PySys_SetObject("stderr", pstderr);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000244 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000245
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000246 _PyImport_Init();
247
Barry Warsaw035574d1997-08-29 22:07:17 +0000248 /* phase 2 of builtins */
Georg Brandl1a3284e2007-12-02 09:40:06 +0000249 _PyImport_FixupExtension("builtins", "builtins");
Barry Warsaw035574d1997-08-29 22:07:17 +0000250
Just van Rossum52e14d62002-12-30 22:08:05 +0000251 _PyImportHooks_Init();
252
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000253 if (install_sigs)
254 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000255
256 initmain(); /* Module __main__ */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000257 if (initstdio() < 0)
258 Py_FatalError(
259 "Py_Initialize: can't initialize sys standard streams");
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000260 if (!Py_NoSiteFlag)
261 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000262
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000263 /* auto-thread-state API, if available */
264#ifdef WITH_THREAD
265 _PyGILState_Init(interp, tstate);
266#endif /* WITH_THREAD */
267
Mark Hammondedd07732003-07-15 23:03:55 +0000268 warnings_module = PyImport_ImportModule("warnings");
Guido van Rossum98297ee2007-11-06 21:34:58 +0000269 if (!warnings_module) {
Mark Hammondedd07732003-07-15 23:03:55 +0000270 PyErr_Clear();
Guido van Rossum98297ee2007-11-06 21:34:58 +0000271 }
272 else {
273 PyObject *o;
274 char *action[8];
275
276 if (Py_BytesWarningFlag > 1)
277 *action = "error";
278 else if (Py_BytesWarningFlag)
279 *action = "default";
280 else
281 *action = "ignore";
282
283 o = PyObject_CallMethod(warnings_module,
284 "simplefilter", "sO",
285 *action, PyExc_BytesWarning);
286 if (o == NULL)
287 Py_FatalError("Py_Initialize: can't initialize"
288 "warning filter for BytesWarning.");
289 Py_DECREF(o);
290 }
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000291
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000292#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000293 /* On Unix, set the file system encoding according to the
294 user's preference, if the CODESET names a well-known
295 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000296 initialized by other means. Also set the encoding of
297 stdin and stdout if these are terminals. */
298
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000299 codeset = nl_langinfo(CODESET);
300 if (codeset && *codeset) {
301 PyObject *enc = PyCodec_Encoder(codeset);
302 if (enc) {
303 codeset = strdup(codeset);
304 Py_DECREF(enc);
305 } else {
306 codeset = NULL;
307 PyErr_Clear();
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000308 }
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000309 } else
310 codeset = NULL;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000311
312 if (codeset) {
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000313 if (!Py_FileSystemDefaultEncoding)
314 Py_FileSystemDefaultEncoding = codeset;
315 else
316 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000317 }
318#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000319}
320
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000321void
322Py_Initialize(void)
323{
324 Py_InitializeEx(1);
325}
326
327
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000328#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000329extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000330#endif
331
Guido van Rossume8432ac2007-07-09 15:04:50 +0000332/* Flush stdout and stderr */
333
Neal Norwitz2bad9702007-08-27 06:19:22 +0000334static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000335flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000336{
337 PyObject *fout = PySys_GetObject("stdout");
338 PyObject *ferr = PySys_GetObject("stderr");
339 PyObject *tmp;
340
Christian Heimes2be03732007-11-15 02:26:46 +0000341 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000342 tmp = PyObject_CallMethod(fout, "flush", "");
343 if (tmp == NULL)
344 PyErr_Clear();
345 else
346 Py_DECREF(tmp);
347 }
348
Christian Heimes2be03732007-11-15 02:26:46 +0000349 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000350 tmp = PyObject_CallMethod(ferr, "flush", "");
351 if (tmp == NULL)
352 PyErr_Clear();
353 else
354 Py_DECREF(tmp);
355 }
356}
357
Guido van Rossum25ce5661997-08-02 03:10:38 +0000358/* Undo the effect of Py_Initialize().
359
360 Beware: if multiple interpreter and/or thread states exist, these
361 are not wiped out; only the current thread and interpreter state
362 are deleted. But since everything else is deleted, those other
363 interpreter and thread states should no longer be used.
364
365 (XXX We should do better, e.g. wipe out all interpreters and
366 threads.)
367
368 Locking: as above.
369
370*/
371
372void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000373Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374{
375 PyInterpreterState *interp;
376 PyThreadState *tstate;
377
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000378 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000379 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380
Tim Peters384fd102001-01-21 03:40:37 +0000381 /* The interpreter is still entirely intact at this point, and the
382 * exit funcs may be relying on that. In particular, if some thread
383 * or exit func is still waiting to do an import, the import machinery
384 * expects Py_IsInitialized() to return true. So don't say the
385 * interpreter is uninitialized until after the exit funcs have run.
386 * Note that Threading.py uses an exit func to do a join on all the
387 * threads created thru it, so this also protects pending imports in
388 * the threads created via Threading.
389 */
Collin Winter670e6922007-03-21 02:57:17 +0000390 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000391 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000392
Guido van Rossume8432ac2007-07-09 15:04:50 +0000393 /* Flush stdout+stderr */
394 flush_std_files();
395
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000396 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000397 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000398 interp = tstate->interp;
399
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000400 /* Disable signal handling */
401 PyOS_FiniInterrupts();
402
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000403 /* drop module references we saved */
Mark Hammondedd07732003-07-15 23:03:55 +0000404 Py_XDECREF(warnings_module);
405 warnings_module = NULL;
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000406
Christian Heimes26855632008-01-27 23:50:43 +0000407 /* Clear type lookup cache */
408 PyType_ClearCache();
409
Guido van Rossume13ddc92003-04-17 17:29:22 +0000410 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000411 * before all modules are destroyed.
412 * XXX If a __del__ or weakref callback is triggered here, and tries to
413 * XXX import a module, bad things can happen, because Python no
414 * XXX longer believes it's initialized.
415 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
416 * XXX is easy to provoke that way. I've also seen, e.g.,
417 * XXX Exception exceptions.ImportError: 'No module named sha'
418 * XXX in <function callback at 0x008F5718> ignored
419 * XXX but I'm unclear on exactly how that one happens. In any case,
420 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000421 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000422 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000423#ifdef COUNT_ALLOCS
424 /* With COUNT_ALLOCS, it helps to run GC multiple times:
425 each collection might release some types from the type
426 list, so they become garbage. */
427 while (PyGC_Collect() > 0)
428 /* nothing */;
429#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000430
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000431 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000432 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000433
Guido van Rossume8432ac2007-07-09 15:04:50 +0000434 /* Flush stdout+stderr (again, in case more was printed) */
435 flush_std_files();
436
Guido van Rossume13ddc92003-04-17 17:29:22 +0000437 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000438 * new-style class definitions, for example.
439 * XXX This is disabled because it caused too many problems. If
440 * XXX a __del__ or weakref callback triggers here, Python code has
441 * XXX a hard time running, because even the sys module has been
442 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
443 * XXX One symptom is a sequence of information-free messages
444 * XXX coming from threads (if a __del__ or callback is invoked,
445 * XXX other threads can execute too, and any exception they encounter
446 * XXX triggers a comedy of errors as subsystem after subsystem
447 * XXX fails to find what it *expects* to find in sys to help report
448 * XXX the exception and consequent unexpected failures). I've also
449 * XXX seen segfaults then, after adding print statements to the
450 * XXX Python code getting called.
451 */
452#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000453 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000454#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000455
Guido van Rossum1707aad1997-12-08 23:43:45 +0000456 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
457 _PyImport_Fini();
458
459 /* Debugging stuff */
460#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000461 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000462#endif
463
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000464 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000465
Tim Peters9cf25ce2003-04-17 15:21:01 +0000466#ifdef Py_TRACE_REFS
467 /* Display all objects still alive -- this can invoke arbitrary
468 * __repr__ overrides, so requires a mostly-intact interpreter.
469 * Alas, a lot of stuff may still be alive now that will be cleaned
470 * up later.
471 */
Tim Peters269b2a62003-04-17 19:52:29 +0000472 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000473 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000474#endif /* Py_TRACE_REFS */
475
Guido van Rossumd922fa42003-04-15 14:10:09 +0000476 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000477 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000478
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000479 /* Now we decref the exception classes. After this point nothing
480 can raise an exception. That's okay, because each Fini() method
481 below has been checked to make sure no exceptions are ever
482 raised.
483 */
484
485 _PyExc_Fini();
486
Christian Heimes7d2ff882007-11-30 14:35:04 +0000487 /* Cleanup auto-thread-state */
488#ifdef WITH_THREAD
489 _PyGILState_Fini();
490#endif /* WITH_THREAD */
491
Guido van Rossumd922fa42003-04-15 14:10:09 +0000492 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000493 PyThreadState_Swap(NULL);
494 PyInterpreterState_Delete(interp);
495
Guido van Rossumd922fa42003-04-15 14:10:09 +0000496 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000497 PyMethod_Fini();
498 PyFrame_Fini();
499 PyCFunction_Fini();
500 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000501 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000502 PySet_Fini();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000503 PyString_Fini();
Neal Norwitz6968b052007-02-27 19:02:19 +0000504 PyBytes_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000505 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000506 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000507 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000508
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000509 /* Cleanup Unicode implementation */
510 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000511
Christian Heimesc8967002007-11-30 10:18:26 +0000512 /* reset file system default encoding */
513 if (!Py_HasFileSystemDefaultEncoding) {
514 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000515 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000516 }
517
Guido van Rossumcc283f51997-08-05 02:22:03 +0000518 /* XXX Still allocated:
519 - various static ad-hoc pointers to interned strings
520 - int and float free list blocks
521 - whatever various modules and libraries allocate
522 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000523
524 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000525
Tim Peters269b2a62003-04-17 19:52:29 +0000526#ifdef Py_TRACE_REFS
527 /* Display addresses (& refcnts) of all objects still alive.
528 * An address can be used to find the repr of the object, printed
529 * above by _Py_PrintReferences.
530 */
531 if (Py_GETENV("PYTHONDUMPREFS"))
532 _Py_PrintReferenceAddresses(stderr);
533#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000534#ifdef PYMALLOC_DEBUG
535 if (Py_GETENV("PYTHONMALLOCSTATS"))
536 _PyObject_DebugMallocStats();
537#endif
538
Guido van Rossumcc283f51997-08-05 02:22:03 +0000539 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000540}
541
542/* Create and initialize a new interpreter and thread, and return the
543 new thread. This requires that Py_Initialize() has been called
544 first.
545
546 Unsuccessful initialization yields a NULL pointer. Note that *no*
547 exception information is available even in this case -- the
548 exception information is held in the thread, and there is no
549 thread.
550
551 Locking: as above.
552
553*/
554
555PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000556Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000557{
558 PyInterpreterState *interp;
559 PyThreadState *tstate, *save_tstate;
560 PyObject *bimod, *sysmod;
561
562 if (!initialized)
563 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
564
565 interp = PyInterpreterState_New();
566 if (interp == NULL)
567 return NULL;
568
569 tstate = PyThreadState_New(interp);
570 if (tstate == NULL) {
571 PyInterpreterState_Delete(interp);
572 return NULL;
573 }
574
575 save_tstate = PyThreadState_Swap(tstate);
576
577 /* XXX The following is lax in error checking */
578
579 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000580 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000581
Georg Brandl1a3284e2007-12-02 09:40:06 +0000582 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000583 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000584 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000585 if (interp->builtins == NULL)
586 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000587 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588 }
589 sysmod = _PyImport_FindExtension("sys", "sys");
590 if (bimod != NULL && sysmod != NULL) {
591 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000592 if (interp->sysdict == NULL)
593 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594 Py_INCREF(interp->sysdict);
595 PySys_SetPath(Py_GetPath());
596 PyDict_SetItemString(interp->sysdict, "modules",
597 interp->modules);
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000598 _PyImportHooks_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000599 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000600 if (!Py_NoSiteFlag)
601 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000602 }
603
604 if (!PyErr_Occurred())
605 return tstate;
606
Thomas Wouters89f507f2006-12-13 04:49:30 +0000607handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608 /* Oops, it didn't work. Undo it all. */
609
610 PyErr_Print();
611 PyThreadState_Clear(tstate);
612 PyThreadState_Swap(save_tstate);
613 PyThreadState_Delete(tstate);
614 PyInterpreterState_Delete(interp);
615
616 return NULL;
617}
618
619/* Delete an interpreter and its last thread. This requires that the
620 given thread state is current, that the thread has no remaining
621 frames, and that it is its interpreter's only remaining thread.
622 It is a fatal error to violate these constraints.
623
624 (Py_Finalize() doesn't have these constraints -- it zaps
625 everything, regardless.)
626
627 Locking: as above.
628
629*/
630
631void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000632Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633{
634 PyInterpreterState *interp = tstate->interp;
635
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000636 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637 Py_FatalError("Py_EndInterpreter: thread is not current");
638 if (tstate->frame != NULL)
639 Py_FatalError("Py_EndInterpreter: thread still has a frame");
640 if (tstate != interp->tstate_head || tstate->next != NULL)
641 Py_FatalError("Py_EndInterpreter: not the last thread");
642
643 PyImport_Cleanup();
644 PyInterpreterState_Clear(interp);
645 PyThreadState_Swap(NULL);
646 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000647}
648
649static char *progname = "python";
650
651void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000652Py_SetProgramName(char *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000653{
654 if (pn && *pn)
655 progname = pn;
656}
657
658char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000659Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000660{
661 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000662}
663
Guido van Rossuma61691e1998-02-06 22:27:24 +0000664static char *default_home = NULL;
665
666void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000667Py_SetPythonHome(char *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000668{
669 default_home = home;
670}
671
672char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000673Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000674{
675 char *home = default_home;
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000676 if (home == NULL && !Py_IgnoreEnvironmentFlag)
677 home = Py_GETENV("PYTHONHOME");
Guido van Rossuma61691e1998-02-06 22:27:24 +0000678 return home;
679}
680
Guido van Rossum6135a871995-01-09 17:53:26 +0000681/* Create __main__ module */
682
683static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000684initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000685{
Guido van Rossum82598051997-03-05 00:20:32 +0000686 PyObject *m, *d;
687 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000688 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000689 Py_FatalError("can't create __main__ module");
690 d = PyModule_GetDict(m);
691 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000692 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000693 if (bimod == NULL ||
694 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000695 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000696 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000697 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000698}
699
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000700/* Import the site module (not into __main__ though) */
701
702static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000703initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000704{
705 PyObject *m, *f;
706 m = PyImport_ImportModule("site");
707 if (m == NULL) {
708 f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +0000709 if (f == NULL || f == Py_None)
710 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000711 if (Py_VerboseFlag) {
712 PyFile_WriteString(
713 "'import site' failed; traceback:\n", f);
714 PyErr_Print();
715 }
716 else {
717 PyFile_WriteString(
718 "'import site' failed; use -v for traceback\n", f);
719 PyErr_Clear();
720 }
721 }
722 else {
723 Py_DECREF(m);
724 }
725}
726
Georg Brandl1a3284e2007-12-02 09:40:06 +0000727/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000728static int
729initstdio(void)
730{
731 PyObject *iomod = NULL, *wrapper;
732 PyObject *bimod = NULL;
733 PyObject *m;
734 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000735 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000736 PyObject * encoding_attr;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000737
738 /* Hack to avoid a nasty recursion issue when Python is invoked
739 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
740 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
741 goto error;
742 }
743 Py_DECREF(m);
744
745 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
746 goto error;
747 }
748 Py_DECREF(m);
749
Georg Brandl1a3284e2007-12-02 09:40:06 +0000750 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000751 goto error;
752 }
753
754 if (!(iomod = PyImport_ImportModule("io"))) {
755 goto error;
756 }
757 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
758 goto error;
759 }
760
Georg Brandl1a3284e2007-12-02 09:40:06 +0000761 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000762 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
763 goto error;
764 }
765
766 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000767 fd = fileno(stdin);
768 /* Under some conditions stdin, stdout and stderr may not be connected
769 * and fileno() may point to an invalid file descriptor. For example
770 * GUI apps don't have valid standard streams by default.
771 */
772 if (fd < 0) {
773#ifdef MS_WINDOWS
774 std = Py_None;
775 Py_INCREF(std);
776#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000777 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000778#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000779 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000780 else {
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000781 if (!(std = PyFile_FromFd(fd, "<stdin>", "r", -1, NULL, NULL,
Christian Heimes58cb1b82007-11-13 02:19:40 +0000782 "\n", 0))) {
783 goto error;
784 }
785 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000786 PySys_SetObject("__stdin__", std);
787 PySys_SetObject("stdin", std);
788 Py_DECREF(std);
789
790 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000791 fd = fileno(stdout);
792 if (fd < 0) {
793#ifdef MS_WINDOWS
794 std = Py_None;
795 Py_INCREF(std);
796#else
797 goto error;
798#endif
799 }
800 else {
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000801 if (!(std = PyFile_FromFd(fd, "<stdout>", "w", -1, NULL, NULL,
Christian Heimes58cb1b82007-11-13 02:19:40 +0000802 "\n", 0))) {
803 goto error;
804 }
805 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000806 PySys_SetObject("__stdout__", std);
807 PySys_SetObject("stdout", std);
808 Py_DECREF(std);
809
Guido van Rossum98297ee2007-11-06 21:34:58 +0000810#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000811 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000812 fd = fileno(stderr);
813 if (fd < 0) {
814#ifdef MS_WINDOWS
815 std = Py_None;
816 Py_INCREF(std);
817#else
818 goto error;
819#endif
820 }
821 else {
Guido van Rossume7fc50f2007-12-03 22:54:21 +0000822 if (!(std = PyFile_FromFd(fd, "<stderr>", "w", -1, NULL, NULL,
Christian Heimes58cb1b82007-11-13 02:19:40 +0000823 "\n", 0))) {
824 goto error;
825 }
826 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000827
828 /* Same as hack above, pre-import stderr's codec to avoid recursion
829 when import.c tries to write to stderr in verbose mode. */
830 encoding_attr = PyObject_GetAttrString(std, "encoding");
831 if (encoding_attr != NULL) {
832 const char * encoding;
833 encoding = PyUnicode_AsString(encoding_attr);
834 if (encoding != NULL) {
835 _PyCodec_Lookup(encoding);
836 }
837 }
838 PyErr_Clear(); /* Not a fatal error if codec isn't available */
839
Christian Heimesdb233082007-11-13 02:34:21 +0000840 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000841 PySys_SetObject("stderr", std);
842 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000843#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000844
Christian Heimes58cb1b82007-11-13 02:19:40 +0000845 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000846 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000847 status = -1;
848 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000849
850 Py_XDECREF(bimod);
851 Py_XDECREF(iomod);
852 return status;
853}
854
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000855/* Parse input from a file and execute it */
856
857int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000858PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000859 PyCompilerFlags *flags)
860{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000861 if (filename == NULL)
862 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000863 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000864 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000865 if (closeit)
866 fclose(fp);
867 return err;
868 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000869 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000870 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000871}
872
873int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000874PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000875{
Guido van Rossum82598051997-03-05 00:20:32 +0000876 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000877 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000878 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000879
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000880 if (flags == NULL) {
881 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000882 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000883 }
Guido van Rossum82598051997-03-05 00:20:32 +0000884 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000885 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000886 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000887 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000888 }
Guido van Rossum82598051997-03-05 00:20:32 +0000889 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000890 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000891 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000892 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000893 }
894 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000895 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000896 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000897 if (ret == E_EOF)
898 return 0;
899 /*
900 if (ret == E_NOMEM)
901 return -1;
902 */
903 }
904}
905
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000906/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000907#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +0000908 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Guido van Rossum45aecf42006-03-15 04:58:47 +0000909 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000910
Thomas Wouters89f507f2006-12-13 04:49:30 +0000911#if 0
912/* Keep an example of flags with future keyword support. */
913#define PARSER_FLAGS(flags) \
914 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
915 PyPARSE_DONT_IMPLY_DEDENT : 0) \
916 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
917 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
918#endif
919
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000920int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000921PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000922{
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000923 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000924 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +0000925 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000926 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000927 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +0000928
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000929 if (fp == stdin) {
930 /* Fetch encoding from sys.stdin */
931 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +0000932 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000933 return -1;
934 oenc = PyObject_GetAttrString(v, "encoding");
935 if (!oenc)
936 return -1;
937 enc = PyUnicode_AsString(oenc);
938 }
Guido van Rossum82598051997-03-05 00:20:32 +0000939 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000940 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000941 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000942 if (v == NULL)
943 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000944 else if (PyUnicode_Check(v))
945 ps1 = PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000946 }
Guido van Rossum82598051997-03-05 00:20:32 +0000947 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000948 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +0000949 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +0000950 if (w == NULL)
951 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +0000952 else if (PyUnicode_Check(w))
953 ps2 = PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000954 }
Neal Norwitz9589ee22006-03-04 19:01:22 +0000955 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000956 if (arena == NULL) {
957 Py_XDECREF(v);
958 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000959 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000960 return -1;
961 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000962 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000963 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000964 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +0000965 Py_XDECREF(v);
966 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000967 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000968 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000969 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000970 if (errcode == E_EOF) {
971 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +0000972 return E_EOF;
973 }
Guido van Rossum82598051997-03-05 00:20:32 +0000974 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000975 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000976 }
Guido van Rossum82598051997-03-05 00:20:32 +0000977 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000978 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +0000979 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000980 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000981 }
Guido van Rossum82598051997-03-05 00:20:32 +0000982 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000983 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +0000984 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000985 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +0000986 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000987 return -1;
988 }
Guido van Rossum82598051997-03-05 00:20:32 +0000989 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000990 return 0;
991}
992
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000993/* Check whether a file maybe a pyc file: Look at the extension,
994 the file type, and, if we may close it, at the first few bytes. */
995
996static int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000997maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +0000998{
999 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1000 return 1;
1001
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001002 /* Only look into the file if we are allowed to close it, since
1003 it then should also be seekable. */
1004 if (closeit) {
1005 /* Read only two bytes of the magic. If the file was opened in
1006 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1007 be read as they are on disk. */
1008 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1009 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001010 /* Mess: In case of -x, the stream is NOT at its start now,
1011 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001012 which makes the current stream position formally undefined,
1013 and a x-platform nightmare.
1014 Unfortunately, we have no direct way to know whether -x
1015 was specified. So we use a terrible hack: if the current
1016 stream position is not 0, we assume -x was specified, and
1017 give up. Bug 132850 on SourceForge spells out the
1018 hopelessness of trying anything else (fseek and ftell
1019 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001020 */
Tim Peters3e876562001-02-11 04:35:39 +00001021 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001022 if (ftell(fp) == 0) {
1023 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001024 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001025 ispyc = 1;
1026 rewind(fp);
1027 }
Tim Peters3e876562001-02-11 04:35:39 +00001028 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001029 }
1030 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001031}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001032
Guido van Rossum0df002c2000-08-27 19:21:52 +00001033int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001034PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001035 PyCompilerFlags *flags)
1036{
Guido van Rossum82598051997-03-05 00:20:32 +00001037 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001038 const char *ext;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001039 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001040
Guido van Rossum82598051997-03-05 00:20:32 +00001041 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001042 if (m == NULL)
1043 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001044 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001045 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001046 PyObject *f;
1047 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001048 if (f == NULL)
1049 return -1;
1050 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1051 Py_DECREF(f);
1052 return -1;
1053 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001054 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001055 Py_DECREF(f);
1056 }
Guido van Rossumfdef2711994-09-14 13:31:04 +00001057 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001058 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001059 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001060 if (closeit)
1061 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001062 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001063 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001064 ret = -1;
1065 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001066 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001067 /* Turn on optimization if a .pyo file is given */
1068 if (strcmp(ext, ".pyo") == 0)
1069 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001070 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001071 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001072 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001073 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001074 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001075 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001076 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001077 ret = -1;
1078 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001079 }
Guido van Rossum82598051997-03-05 00:20:32 +00001080 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001081 ret = 0;
1082 done:
1083 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1084 PyErr_Clear();
1085 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001086}
1087
1088int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001089PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001090{
Guido van Rossum82598051997-03-05 00:20:32 +00001091 PyObject *m, *d, *v;
1092 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001093 if (m == NULL)
1094 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001095 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001096 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001097 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001098 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001099 return -1;
1100 }
Guido van Rossum82598051997-03-05 00:20:32 +00001101 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001102 return 0;
1103}
1104
Barry Warsaw035574d1997-08-29 22:07:17 +00001105static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001106parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1107 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001108{
1109 long hold;
1110 PyObject *v;
1111
1112 /* old style errors */
1113 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001114 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001115 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001116
1117 /* new style errors. `err' is an instance */
1118
1119 if (! (v = PyObject_GetAttrString(err, "msg")))
1120 goto finally;
1121 *message = v;
1122
1123 if (!(v = PyObject_GetAttrString(err, "filename")))
1124 goto finally;
1125 if (v == Py_None)
1126 *filename = NULL;
Kurt B. Kaiser43b15092008-01-05 04:32:22 +00001127 else if (! (*filename = PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001128 goto finally;
1129
1130 Py_DECREF(v);
1131 if (!(v = PyObject_GetAttrString(err, "lineno")))
1132 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001133 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001134 Py_DECREF(v);
1135 v = NULL;
1136 if (hold < 0 && PyErr_Occurred())
1137 goto finally;
1138 *lineno = (int)hold;
1139
1140 if (!(v = PyObject_GetAttrString(err, "offset")))
1141 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001142 if (v == Py_None) {
1143 *offset = -1;
1144 Py_DECREF(v);
1145 v = NULL;
1146 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001147 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001148 Py_DECREF(v);
1149 v = NULL;
1150 if (hold < 0 && PyErr_Occurred())
1151 goto finally;
1152 *offset = (int)hold;
1153 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001154
1155 if (!(v = PyObject_GetAttrString(err, "text")))
1156 goto finally;
1157 if (v == Py_None)
1158 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001159 else if (!PyUnicode_Check(v) ||
1160 !(*text = PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001161 goto finally;
1162 Py_DECREF(v);
1163 return 1;
1164
1165finally:
1166 Py_XDECREF(v);
1167 return 0;
1168}
1169
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001170void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001171PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001172{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001173 PyErr_PrintEx(1);
1174}
1175
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001176static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001177print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001178{
1179 char *nl;
1180 if (offset >= 0) {
1181 if (offset > 0 && offset == (int)strlen(text))
1182 offset--;
1183 for (;;) {
1184 nl = strchr(text, '\n');
1185 if (nl == NULL || nl-text >= offset)
1186 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001187 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001188 text = nl+1;
1189 }
1190 while (*text == ' ' || *text == '\t') {
1191 text++;
1192 offset--;
1193 }
1194 }
1195 PyFile_WriteString(" ", f);
1196 PyFile_WriteString(text, f);
1197 if (*text == '\0' || text[strlen(text)-1] != '\n')
1198 PyFile_WriteString("\n", f);
1199 if (offset == -1)
1200 return;
1201 PyFile_WriteString(" ", f);
1202 offset--;
1203 while (offset > 0) {
1204 PyFile_WriteString(" ", f);
1205 offset--;
1206 }
1207 PyFile_WriteString("^\n", f);
1208}
1209
Guido van Rossum66e8e862001-03-23 17:54:43 +00001210static void
1211handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001212{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001213 PyObject *exception, *value, *tb;
1214 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001215
Guido van Rossumd8faa362007-04-27 19:54:29 +00001216 if (Py_InspectFlag)
1217 /* Don't exit if -i flag was given. This flag is set to 0
1218 * when entering interactive mode for inspecting. */
1219 return;
1220
Guido van Rossum66e8e862001-03-23 17:54:43 +00001221 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001222 fflush(stdout);
1223 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001224 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001225 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001226 /* The error code should be in the `code' attribute. */
1227 PyObject *code = PyObject_GetAttrString(value, "code");
1228 if (code) {
1229 Py_DECREF(value);
1230 value = code;
1231 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001232 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001233 }
1234 /* If we failed to dig out the 'code' attribute,
1235 just let the else clause below print the error. */
1236 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001237 if (PyLong_Check(value))
1238 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001239 else {
1240 PyObject_Print(value, stderr, Py_PRINT_RAW);
1241 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001242 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001243 }
Tim Peterscf615b52003-04-19 18:47:02 +00001244 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001245 /* Restore and clear the exception info, in order to properly decref
1246 * the exception, value, and traceback. If we just exit instead,
1247 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1248 * some finalizers from running.
1249 */
Tim Peterscf615b52003-04-19 18:47:02 +00001250 PyErr_Restore(exception, value, tb);
1251 PyErr_Clear();
1252 Py_Exit(exitcode);
1253 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001254}
1255
1256void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001257PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001258{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001259 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001260
1261 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1262 handle_system_exit();
1263 }
Guido van Rossum82598051997-03-05 00:20:32 +00001264 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001265 if (exception == NULL)
1266 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001267 PyErr_NormalizeException(&exception, &v, &tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001268 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001269 return;
Guido van Rossum9d785502006-03-07 18:31:44 +00001270 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001271 if (set_sys_last_vars) {
1272 PySys_SetObject("last_type", exception);
1273 PySys_SetObject("last_value", v);
Guido van Rossumc5724de2007-10-10 21:38:59 +00001274 PySys_SetObject("last_traceback", tb ? tb : Py_None);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001275 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001276 hook = PySys_GetObject("excepthook");
1277 if (hook) {
Raymond Hettinger8ae46892003-10-12 19:09:37 +00001278 PyObject *args = PyTuple_Pack(3,
Guido van Rossum9d785502006-03-07 18:31:44 +00001279 exception, v, tb ? tb : Py_None);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001280 PyObject *result = PyEval_CallObject(hook, args);
1281 if (result == NULL) {
1282 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001283 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1284 handle_system_exit();
1285 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001286 PyErr_Fetch(&exception2, &v2, &tb2);
1287 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001288 /* It should not be possible for exception2 or v2
1289 to be NULL. However PyErr_Display() can't
1290 tolerate NULLs, so just be safe. */
1291 if (exception2 == NULL) {
1292 exception2 = Py_None;
1293 Py_INCREF(exception2);
1294 }
1295 if (v2 == NULL) {
1296 v2 = Py_None;
1297 Py_INCREF(v2);
1298 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001299 fflush(stdout);
1300 PySys_WriteStderr("Error in sys.excepthook:\n");
1301 PyErr_Display(exception2, v2, tb2);
1302 PySys_WriteStderr("\nOriginal exception was:\n");
1303 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001304 Py_DECREF(exception2);
1305 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001306 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001307 }
1308 Py_XDECREF(result);
1309 Py_XDECREF(args);
1310 } else {
1311 PySys_WriteStderr("sys.excepthook is missing\n");
1312 PyErr_Display(exception, v, tb);
1313 }
1314 Py_XDECREF(exception);
1315 Py_XDECREF(v);
1316 Py_XDECREF(tb);
1317}
1318
Thomas Wouters477c8d52006-05-27 19:21:47 +00001319void
1320PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001321{
1322 int err = 0;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001323 PyObject *f = PySys_GetObject("stderr");
Armin Rigo5d2c6832004-03-22 20:16:58 +00001324 Py_INCREF(value);
Christian Heimes2be03732007-11-15 02:26:46 +00001325 if (f == Py_None) {
1326 /* pass */
1327 }
1328 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001329 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001330 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001331 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001332 else {
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001333 fflush(stdout);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001334 if (tb && tb != Py_None)
1335 err = PyTraceBack_Print(tb, f);
Barry Warsaw36b8f941997-08-26 18:09:48 +00001336 if (err == 0 &&
Armin Rigo5d2c6832004-03-22 20:16:58 +00001337 PyObject_HasAttrString(value, "print_file_and_line"))
Barry Warsaw36b8f941997-08-26 18:09:48 +00001338 {
Guido van Rossum82598051997-03-05 00:20:32 +00001339 PyObject *message;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001340 const char *filename, *text;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001341 int lineno, offset;
Armin Rigo5d2c6832004-03-22 20:16:58 +00001342 if (!parse_syntax_error(value, &message, &filename,
Barry Warsaw035574d1997-08-29 22:07:17 +00001343 &lineno, &offset, &text))
Guido van Rossum82598051997-03-05 00:20:32 +00001344 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001345 else {
1346 char buf[10];
Guido van Rossum82598051997-03-05 00:20:32 +00001347 PyFile_WriteString(" File \"", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001348 if (filename == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +00001349 PyFile_WriteString("<string>", f);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001350 else
Guido van Rossum82598051997-03-05 00:20:32 +00001351 PyFile_WriteString(filename, f);
1352 PyFile_WriteString("\", line ", f);
Jeremy Hylton518ab1c2001-11-28 20:42:20 +00001353 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
Guido van Rossum82598051997-03-05 00:20:32 +00001354 PyFile_WriteString(buf, f);
1355 PyFile_WriteString("\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001356 if (text != NULL)
1357 print_error_text(f, offset, text);
Armin Rigo5d2c6832004-03-22 20:16:58 +00001358 Py_DECREF(value);
1359 value = message;
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001360 /* Can't be bothered to check all those
1361 PyFile_WriteString() calls */
1362 if (PyErr_Occurred())
1363 err = -1;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001364 }
1365 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001366 if (err) {
1367 /* Don't do anything else */
1368 }
Brett Cannonbf364092006-03-01 04:25:17 +00001369 else if (PyExceptionClass_Check(exception)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001370 PyObject* moduleName;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001371 char* className = PyExceptionClass_Name(exception);
1372 if (className != NULL) {
1373 char *dot = strrchr(className, '.');
1374 if (dot != NULL)
1375 className = dot+1;
1376 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001377
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001378 moduleName = PyObject_GetAttrString(exception, "__module__");
Guido van Rossumc5724de2007-10-10 21:38:59 +00001379 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1380 {
1381 Py_DECREF(moduleName);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001382 err = PyFile_WriteString("<unknown>", f);
Guido van Rossumc5724de2007-10-10 21:38:59 +00001383 }
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001384 else {
Guido van Rossumc5724de2007-10-10 21:38:59 +00001385 char* modstr = PyUnicode_AsString(moduleName);
Georg Brandl1a3284e2007-12-02 09:40:06 +00001386 if (modstr && strcmp(modstr, "builtins"))
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001387 {
1388 err = PyFile_WriteString(modstr, f);
1389 err += PyFile_WriteString(".", f);
1390 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001391 Py_DECREF(moduleName);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001392 }
1393 if (err == 0) {
1394 if (className == NULL)
1395 err = PyFile_WriteString("<unknown>", f);
1396 else
Brett Cannonbf364092006-03-01 04:25:17 +00001397 err = PyFile_WriteString(className, f);
Barry Warsaw2f5f6a21997-09-16 21:42:03 +00001398 }
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001399 }
1400 else
1401 err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
Brett Cannon2e63b732006-03-02 18:34:57 +00001402 if (err == 0 && (value != Py_None)) {
Thomas Heller519a0422007-11-15 20:48:54 +00001403 PyObject *s = PyObject_Str(value);
Brett Cannon2e63b732006-03-02 18:34:57 +00001404 /* only print colon if the str() of the
1405 object is not the empty string
1406 */
1407 if (s == NULL)
1408 err = -1;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001409 else if (!PyUnicode_Check(s) ||
1410 PyUnicode_GetSize(s) != 0)
Brett Cannon2e63b732006-03-02 18:34:57 +00001411 err = PyFile_WriteString(": ", f);
1412 if (err == 0)
1413 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1414 Py_XDECREF(s);
Guido van Rossum262e1241995-02-07 15:30:45 +00001415 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001416 /* try to write a newline in any case */
1417 err += PyFile_WriteString("\n", f);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001418 }
Armin Rigo5d2c6832004-03-22 20:16:58 +00001419 Py_DECREF(value);
Guido van Rossum78a1ed31997-05-22 22:35:04 +00001420 /* If an error happened here, don't show it.
1421 XXX This is wrong, but too many callers rely on this behavior. */
1422 if (err != 0)
1423 PyErr_Clear();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001424}
1425
Guido van Rossum82598051997-03-05 00:20:32 +00001426PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001427PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001428 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001429{
Neal Norwitze92fba02006-03-04 18:52:26 +00001430 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001431 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001432 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001433 if (arena == NULL)
1434 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001435
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001436 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001437 if (mod != NULL)
1438 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001439 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001440 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001441}
1442
1443PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001444PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001445 PyObject *locals, int closeit, PyCompilerFlags *flags)
1446{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001447 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001448 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001449 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001450 if (arena == NULL)
1451 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001452
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001453 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001454 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001455 if (closeit)
1456 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001457 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001458 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001459 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001460 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001461 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001462 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001463 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001464}
1465
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001466static void
1467flush_io(void)
1468{
1469 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001470 PyObject *type, *value, *traceback;
1471
1472 /* Save the current exception */
1473 PyErr_Fetch(&type, &value, &traceback);
1474
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001475 f = PySys_GetObject("stderr");
1476 if (f != NULL) {
1477 r = PyObject_CallMethod(f, "flush", "");
1478 if (r)
1479 Py_DECREF(r);
1480 else
1481 PyErr_Clear();
1482 }
1483 f = PySys_GetObject("stdout");
1484 if (f != NULL) {
1485 r = PyObject_CallMethod(f, "flush", "");
1486 if (r)
1487 Py_DECREF(r);
1488 else
1489 PyErr_Clear();
1490 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001491
1492 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001493}
1494
Guido van Rossum82598051997-03-05 00:20:32 +00001495static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001496run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001497 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001498{
Guido van Rossum82598051997-03-05 00:20:32 +00001499 PyCodeObject *co;
1500 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001501 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001502 if (co == NULL)
1503 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001504 v = PyEval_EvalCode(co, globals, locals);
1505 Py_DECREF(co);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001506 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001507 return v;
1508}
1509
Guido van Rossum82598051997-03-05 00:20:32 +00001510static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001511run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001512 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001513{
Guido van Rossum82598051997-03-05 00:20:32 +00001514 PyCodeObject *co;
1515 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001516 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001517 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001518
Guido van Rossum82598051997-03-05 00:20:32 +00001519 magic = PyMarshal_ReadLongFromFile(fp);
1520 if (magic != PyImport_GetMagicNumber()) {
1521 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001522 "Bad magic number in .pyc file");
1523 return NULL;
1524 }
Guido van Rossum82598051997-03-05 00:20:32 +00001525 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001526 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001527 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001528 if (v == NULL || !PyCode_Check(v)) {
1529 Py_XDECREF(v);
1530 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001531 "Bad code object in .pyc file");
1532 return NULL;
1533 }
Guido van Rossum82598051997-03-05 00:20:32 +00001534 co = (PyCodeObject *)v;
1535 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001536 if (v && flags)
1537 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001538 Py_DECREF(co);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001539 flush_io();
Guido van Rossumfdef2711994-09-14 13:31:04 +00001540 return v;
1541}
1542
Guido van Rossum82598051997-03-05 00:20:32 +00001543PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001544Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001545 PyCompilerFlags *flags)
1546{
Guido van Rossum82598051997-03-05 00:20:32 +00001547 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001548 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001549 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001550 if (arena == NULL)
1551 return NULL;
1552
1553 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001554 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001555 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001556 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001557 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001558 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001559 PyObject *result = PyAST_mod2obj(mod);
1560 PyArena_Free(arena);
1561 return result;
1562 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001563 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001564 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001565 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001566}
1567
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001568struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001569Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001570{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001571 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001572 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001573 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001574 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001575 if (arena == NULL)
1576 return NULL;
1577
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001578 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001579 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001580 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001581 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001582 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001583 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001584 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001585 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001586 return st;
1587}
1588
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001589/* Preferred access to parser is through AST. */
1590mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001591PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001592 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001593{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001594 mod_ty mod;
1595 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001596 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001597
1598 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001599 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001600 &iflags);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001601 if (n) {
Christian Heimes4d6ec852008-03-26 22:34:47 +00001602 if (flags) {
1603 flags->cf_flags |= iflags & PyCF_MASK;
1604 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001605 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001606 PyNode_Free(n);
1607 return mod;
1608 }
1609 else {
1610 err_input(&err);
1611 return NULL;
1612 }
1613}
1614
1615mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001616PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1617 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001618 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001619 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001620{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001621 mod_ty mod;
1622 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001623 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001624
Christian Heimes4d6ec852008-03-26 22:34:47 +00001625 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001626 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001627 start, ps1, ps2, &err, &iflags);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001628 if (n) {
Christian Heimes4d6ec852008-03-26 22:34:47 +00001629 if (flags) {
1630 flags->cf_flags |= iflags & PyCF_MASK;
1631 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001632 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001633 PyNode_Free(n);
1634 return mod;
1635 }
1636 else {
1637 err_input(&err);
1638 if (errcode)
1639 *errcode = err.error;
1640 return NULL;
1641 }
1642}
1643
Guido van Rossuma110aa61994-08-29 12:50:44 +00001644/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001645
Guido van Rossuma110aa61994-08-29 12:50:44 +00001646node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001647PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001648{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001649 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001650 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1651 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001652 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001653 if (n == NULL)
1654 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001655
Guido van Rossuma110aa61994-08-29 12:50:44 +00001656 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001657}
1658
Guido van Rossuma110aa61994-08-29 12:50:44 +00001659/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001660
Guido van Rossuma110aa61994-08-29 12:50:44 +00001661node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001662PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001663{
Tim Petersfe2127d2001-07-16 05:37:24 +00001664 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001665 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1666 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001667 if (n == NULL)
1668 err_input(&err);
1669 return n;
1670}
1671
1672node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001673PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001674 int start, int flags)
1675{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001676 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001677 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1678 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001679 if (n == NULL)
1680 err_input(&err);
1681 return n;
1682}
1683
1684node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001685PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001686{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001687 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001688}
1689
Guido van Rossum66ebd912003-04-17 16:02:26 +00001690/* May want to move a more generalized form of this to parsetok.c or
1691 even parser modules. */
1692
1693void
1694PyParser_SetError(perrdetail *err)
1695{
1696 err_input(err);
1697}
1698
Guido van Rossuma110aa61994-08-29 12:50:44 +00001699/* Set the error appropriate to the given input error code (see errcode.h) */
1700
1701static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001702err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001703{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001704 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001705 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001706 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001707 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001708 switch (err->error) {
1709 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001710 errtype = PyExc_IndentationError;
1711 if (err->expected == INDENT)
1712 msg = "expected an indented block";
1713 else if (err->token == INDENT)
1714 msg = "unexpected indent";
1715 else if (err->token == DEDENT)
1716 msg = "unexpected unindent";
1717 else {
1718 errtype = PyExc_SyntaxError;
1719 msg = "invalid syntax";
1720 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001721 break;
1722 case E_TOKEN:
1723 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001724 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001725 case E_EOFS:
1726 msg = "EOF while scanning triple-quoted string";
1727 break;
1728 case E_EOLS:
1729 msg = "EOL while scanning single-quoted string";
1730 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001731 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001732 if (!PyErr_Occurred())
1733 PyErr_SetNone(PyExc_KeyboardInterrupt);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001734 return;
1735 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001736 PyErr_NoMemory();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001737 return;
1738 case E_EOF:
1739 msg = "unexpected EOF while parsing";
1740 break;
Fred Drake85f36392000-07-11 17:53:00 +00001741 case E_TABSPACE:
1742 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001743 msg = "inconsistent use of tabs and spaces in indentation";
1744 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001745 case E_OVERFLOW:
1746 msg = "expression too long";
1747 break;
Fred Drake85f36392000-07-11 17:53:00 +00001748 case E_DEDENT:
1749 errtype = PyExc_IndentationError;
1750 msg = "unindent does not match any outer indentation level";
1751 break;
1752 case E_TOODEEP:
1753 errtype = PyExc_IndentationError;
1754 msg = "too many levels of indentation";
1755 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001756 case E_DECODE: {
1757 PyObject *type, *value, *tb;
1758 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001759 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001760 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001761 if (u != NULL) {
Guido van Rossumc5724de2007-10-10 21:38:59 +00001762 msg = PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001763 }
1764 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001765 if (msg == NULL)
1766 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001767 Py_XDECREF(type);
1768 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001769 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001770 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001771 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001772 case E_LINECONT:
1773 msg = "unexpected character after line continuation character";
1774 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001775
1776 case E_IDENTIFIER:
1777 msg = "invalid character in identifier";
1778 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001779 default:
1780 fprintf(stderr, "error=%d\n", err->error);
1781 msg = "unknown parsing error";
1782 break;
1783 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001784 /* err->text may not be UTF-8 in case of decoding errors.
1785 Explicitly convert to an object. */
1786 if (!err->text) {
1787 errtext = Py_None;
1788 Py_INCREF(Py_None);
1789 } else {
1790 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1791 "replace");
1792 }
1793 v = Py_BuildValue("(ziiN)", err->filename,
1794 err->lineno, err->offset, errtext);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001795 if (err->text != NULL) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001796 PyObject_FREE(err->text);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797 err->text = NULL;
1798 }
1799 w = NULL;
1800 if (v != NULL)
1801 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001802 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001803 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001804 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001805 Py_XDECREF(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001806}
1807
1808/* Print fatal error message and abort */
1809
1810void
Tim Peters7c321a82002-07-09 02:57:01 +00001811Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001812{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001813 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001814 if (PyErr_Occurred()) {
1815 PyErr_Print();
1816 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001817#ifdef MS_WINDOWS
Guido van Rossum23c94461997-05-22 20:21:30 +00001818 OutputDebugString("Fatal Python error: ");
Guido van Rossuma44823b1995-03-14 15:01:17 +00001819 OutputDebugString(msg);
1820 OutputDebugString("\n");
Guido van Rossum0ba35361998-08-13 13:33:16 +00001821#ifdef _DEBUG
1822 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00001823#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001824#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001825 abort();
1826}
1827
1828/* Clean up and exit */
1829
Guido van Rossuma110aa61994-08-29 12:50:44 +00001830#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00001831#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00001832#endif
1833
Collin Winter670e6922007-03-21 02:57:17 +00001834static void (*pyexitfunc)(void) = NULL;
1835/* For the atexit module. */
1836void _Py_PyAtExit(void (*func)(void))
1837{
1838 pyexitfunc = func;
1839}
1840
1841static void
1842call_py_exitfuncs(void)
1843{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001844 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00001845 return;
1846
1847 (*pyexitfunc)();
1848 PyErr_Clear();
1849}
1850
Guido van Rossum2dcfc961998-10-01 16:01:57 +00001851#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001852static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00001853static int nexitfuncs = 0;
1854
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001855int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00001856{
1857 if (nexitfuncs >= NEXITFUNCS)
1858 return -1;
1859 exitfuncs[nexitfuncs++] = func;
1860 return 0;
1861}
1862
Guido van Rossumcc283f51997-08-05 02:22:03 +00001863static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001864call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00001865{
Guido van Rossum1662dd51994-09-07 14:38:28 +00001866 while (nexitfuncs > 0)
1867 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00001868
1869 fflush(stdout);
1870 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001871}
1872
1873void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001874Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001875{
Guido van Rossumcc283f51997-08-05 02:22:03 +00001876 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001877
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001878 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001879}
1880
Guido van Rossumf1dc5661993-07-05 10:31:29 +00001881static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001882initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001883{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001884#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001885 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001886#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00001887#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001888 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00001889#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001890#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001891 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00001892#endif
Guido van Rossum82598051997-03-05 00:20:32 +00001893 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00001894}
1895
Guido van Rossum7433b121997-02-14 19:45:36 +00001896
1897/*
1898 * The file descriptor fd is considered ``interactive'' if either
1899 * a) isatty(fd) is TRUE, or
1900 * b) the -i flag was given, and the filename associated with
1901 * the descriptor is NULL or "<stdin>" or "???".
1902 */
1903int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001904Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00001905{
1906 if (isatty((int)fileno(fp)))
1907 return 1;
1908 if (!Py_InteractiveFlag)
1909 return 0;
1910 return (filename == NULL) ||
1911 (strcmp(filename, "<stdin>") == 0) ||
1912 (strcmp(filename, "???") == 0);
1913}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001914
1915
Tim Petersd08e3822003-04-17 15:24:21 +00001916#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001917#if defined(WIN32) && defined(_MSC_VER)
1918
1919/* Stack checking for Microsoft C */
1920
1921#include <malloc.h>
1922#include <excpt.h>
1923
Fred Drakee8de31c2000-08-31 05:38:39 +00001924/*
1925 * Return non-zero when we run out of memory on the stack; zero otherwise.
1926 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001927int
Fred Drake399739f2000-08-31 05:52:44 +00001928PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001929{
1930 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00001931 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001932 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00001933 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001934 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00001935 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00001936 EXCEPTION_EXECUTE_HANDLER :
1937 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00001938 int errcode = _resetstkoflw();
1939 if (errcode)
1940 {
1941 Py_FatalError("Could not reset the stack!");
1942 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00001943 }
1944 return 1;
1945}
1946
1947#endif /* WIN32 && _MSC_VER */
1948
1949/* Alternate implementations can be added here... */
1950
1951#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00001952
1953
1954/* Wrappers around sigaction() or signal(). */
1955
1956PyOS_sighandler_t
1957PyOS_getsig(int sig)
1958{
1959#ifdef HAVE_SIGACTION
1960 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001961 if (sigaction(sig, NULL, &context) == -1)
1962 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00001963 return context.sa_handler;
1964#else
1965 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00001966/* Special signal handling for the secure CRT in Visual Studio 2005 */
1967#if defined(_MSC_VER) && _MSC_VER >= 1400
1968 switch (sig) {
1969 /* Only these signals are valid */
1970 case SIGINT:
1971 case SIGILL:
1972 case SIGFPE:
1973 case SIGSEGV:
1974 case SIGTERM:
1975 case SIGBREAK:
1976 case SIGABRT:
1977 break;
1978 /* Don't call signal() with other values or it will assert */
1979 default:
1980 return SIG_ERR;
1981 }
1982#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00001983 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001984 if (handler != SIG_ERR)
1985 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00001986 return handler;
1987#endif
1988}
1989
1990PyOS_sighandler_t
1991PyOS_setsig(int sig, PyOS_sighandler_t handler)
1992{
1993#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001994 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00001995 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00001996 sigemptyset(&context.sa_mask);
1997 context.sa_flags = 0;
1998 if (sigaction(sig, &context, &ocontext) == -1)
1999 return SIG_ERR;
2000 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002001#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002002 PyOS_sighandler_t oldhandler;
2003 oldhandler = signal(sig, handler);
2004#ifdef HAVE_SIGINTERRUPT
2005 siginterrupt(sig, 1);
2006#endif
2007 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002008#endif
2009}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002010
2011/* Deprecated C API functions still provided for binary compatiblity */
2012
2013#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002014PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002015PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2016{
2017 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2018}
2019
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002020#undef PyParser_SimpleParseString
2021PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002022PyParser_SimpleParseString(const char *str, int start)
2023{
2024 return PyParser_SimpleParseStringFlags(str, start, 0);
2025}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002026
2027#undef PyRun_AnyFile
2028PyAPI_FUNC(int)
2029PyRun_AnyFile(FILE *fp, const char *name)
2030{
2031 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2032}
2033
2034#undef PyRun_AnyFileEx
2035PyAPI_FUNC(int)
2036PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2037{
2038 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2039}
2040
2041#undef PyRun_AnyFileFlags
2042PyAPI_FUNC(int)
2043PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2044{
2045 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2046}
2047
2048#undef PyRun_File
2049PyAPI_FUNC(PyObject *)
2050PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2051{
2052 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
2053}
2054
2055#undef PyRun_FileEx
2056PyAPI_FUNC(PyObject *)
2057PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2058{
2059 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
2060}
2061
2062#undef PyRun_FileFlags
2063PyAPI_FUNC(PyObject *)
2064PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2065 PyCompilerFlags *flags)
2066{
2067 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
2068}
2069
2070#undef PyRun_SimpleFile
2071PyAPI_FUNC(int)
2072PyRun_SimpleFile(FILE *f, const char *p)
2073{
2074 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2075}
2076
2077#undef PyRun_SimpleFileEx
2078PyAPI_FUNC(int)
2079PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2080{
2081 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2082}
2083
2084
2085#undef PyRun_String
2086PyAPI_FUNC(PyObject *)
2087PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2088{
2089 return PyRun_StringFlags(str, s, g, l, NULL);
2090}
2091
2092#undef PyRun_SimpleString
2093PyAPI_FUNC(int)
2094PyRun_SimpleString(const char *s)
2095{
2096 return PyRun_SimpleStringFlags(s, NULL);
2097}
2098
2099#undef Py_CompileString
2100PyAPI_FUNC(PyObject *)
2101Py_CompileString(const char *str, const char *p, int s)
2102{
2103 return Py_CompileStringFlags(str, p, s, NULL);
2104}
2105
2106#undef PyRun_InteractiveOne
2107PyAPI_FUNC(int)
2108PyRun_InteractiveOne(FILE *f, const char *p)
2109{
2110 return PyRun_InteractiveOneFlags(f, p, NULL);
2111}
2112
2113#undef PyRun_InteractiveLoop
2114PyAPI_FUNC(int)
2115PyRun_InteractiveLoop(FILE *f, const char *p)
2116{
2117 return PyRun_InteractiveLoopFlags(f, p, NULL);
2118}
2119
2120#ifdef __cplusplus
2121}
2122#endif