blob: ec2c6caea3fd87b3419a09e4a3a0376412407c39 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Antoine Pitroucefb3162009-10-20 22:08:36 +000021#include "abstract.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000022
Thomas Wouters0e3f5912006-08-11 14:57:12 +000023#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000024#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000026
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000027#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000028#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000029#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000030
Martin v. Löwis73d538b2003-03-05 15:13:47 +000031#ifdef HAVE_LANGINFO_H
32#include <locale.h>
33#include <langinfo.h>
34#endif
35
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000036#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000037#undef BYTE
38#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000039#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000040#endif
41
Neal Norwitz4281cef2006-03-04 19:58:13 +000042#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000044#else /* Py_REF_DEBUG */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000045#define PRINT_TOTAL_REFS() fprintf(stderr, \
46 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
47 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000048#endif
49
50#ifdef __cplusplus
51extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000052#endif
53
Martin v. Löwis790465f2008-04-05 20:41:37 +000054extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000055
Guido van Rossum82598051997-03-05 00:20:32 +000056extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000057
Guido van Rossumb73cc041993-11-01 16:28:59 +000058/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000059static void initmain(void);
60static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000061static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000062static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000063static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000064 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000065static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000066 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000067static void err_input(perrdetail *);
68static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000069static void call_py_exitfuncs(void);
Antoine Pitroucefb3162009-10-20 22:08:36 +000070static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000071static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000072extern void _PyUnicode_Init(void);
73extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000074extern int _PyLong_Init(void);
75extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000084int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000085int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000086int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000087int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000088int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000089int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000090int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000091int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000092int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000093int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000094
Christian Heimes33fe8092008-04-13 13:53:33 +000095/* PyModule_GetWarningsModule is no longer necessary as of 2.6
96since _warnings is builtin. This API should not be used. */
97PyObject *
98PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000099{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000100 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000101}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000102
Guido van Rossum25ce5661997-08-02 03:10:38 +0000103static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000104
Thomas Wouters7e474022000-07-16 12:04:32 +0000105/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106
107int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000108Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000110 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111}
112
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113/* Global initializations. Can be undone by Py_Finalize(). Don't
114 call this twice without an intervening Py_Finalize() call. When
115 initializations fail, a fatal error is issued and the function does
116 not return. On return, the first thread and interpreter state have
117 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119 Locking: you must hold the interpreter lock while calling this.
120 (If the lock has not yet been initialized, that's equivalent to
121 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000125static int
126add_flag(int flag, const char *envs)
127{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000128 int env = atoi(envs);
129 if (flag < env)
130 flag = env;
131 if (flag < 1)
132 flag = 1;
133 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000134}
135
Christian Heimes5833a2f2008-10-30 21:40:04 +0000136#if defined(HAVE_LANGINFO_H) && defined(CODESET)
137static char*
138get_codeset(void)
139{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000140 char* codeset;
141 PyObject *codec, *name;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000142
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000143 codeset = nl_langinfo(CODESET);
144 if (!codeset || codeset[0] == '\0')
145 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000146
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000147 codec = _PyCodec_Lookup(codeset);
148 if (!codec)
149 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000150
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000151 name = PyObject_GetAttrString(codec, "name");
152 Py_CLEAR(codec);
153 if (!name)
154 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000155
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000156 codeset = strdup(_PyUnicode_AsString(name));
157 Py_DECREF(name);
158 return codeset;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000159
160error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000161 Py_XDECREF(codec);
162 PyErr_Clear();
163 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000164}
165#endif
166
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000168Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000169{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000170 PyInterpreterState *interp;
171 PyThreadState *tstate;
172 PyObject *bimod, *sysmod, *pstderr;
173 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000174#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000175 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000176#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000177 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000178
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000179 if (initialized)
180 return;
181 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000182
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000183#ifdef HAVE_SETLOCALE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000184 /* Set up the LC_CTYPE locale, so we can obtain
185 the locale's charset without having to switch
186 locales. */
187 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000188#endif
189
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000190 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
191 Py_DebugFlag = add_flag(Py_DebugFlag, p);
192 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
193 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
194 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
195 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
196 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
197 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000198
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000199 interp = PyInterpreterState_New();
200 if (interp == NULL)
201 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000202
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000203 tstate = PyThreadState_New(interp);
204 if (tstate == NULL)
205 Py_FatalError("Py_Initialize: can't make first thread");
206 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000207
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000208 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000209
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000210 if (!_PyFrame_Init())
211 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000212
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000213 if (!_PyLong_Init())
214 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000215
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000216 if (!PyByteArray_Init())
217 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000218
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000219 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000220
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000221 interp->modules = PyDict_New();
222 if (interp->modules == NULL)
223 Py_FatalError("Py_Initialize: can't make modules dictionary");
224 interp->modules_reloading = PyDict_New();
225 if (interp->modules_reloading == NULL)
226 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000227
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000228 /* Init Unicode implementation; relies on the codec registry */
229 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000230
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000231 bimod = _PyBuiltin_Init();
232 if (bimod == NULL)
233 Py_FatalError("Py_Initialize: can't initialize builtins modules");
234 _PyImport_FixupExtension(bimod, "builtins", "builtins");
235 interp->builtins = PyModule_GetDict(bimod);
236 if (interp->builtins == NULL)
237 Py_FatalError("Py_Initialize: can't initialize builtins dict");
238 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000239
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000240 /* initialize builtin exceptions */
241 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000242
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000243 sysmod = _PySys_Init();
244 if (sysmod == NULL)
245 Py_FatalError("Py_Initialize: can't initialize sys");
246 interp->sysdict = PyModule_GetDict(sysmod);
247 if (interp->sysdict == NULL)
248 Py_FatalError("Py_Initialize: can't initialize sys dict");
249 Py_INCREF(interp->sysdict);
250 _PyImport_FixupExtension(sysmod, "sys", "sys");
251 PySys_SetPath(Py_GetPath());
252 PyDict_SetItemString(interp->sysdict, "modules",
253 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000254
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000255 /* Set up a preliminary stderr printer until we have enough
256 infrastructure for the io module in place. */
257 pstderr = PyFile_NewStdPrinter(fileno(stderr));
258 if (pstderr == NULL)
259 Py_FatalError("Py_Initialize: can't set preliminary stderr");
260 PySys_SetObject("stderr", pstderr);
261 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000262
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000263 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000264
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000265 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000266
Martin v. Löwis011e8422009-05-05 04:43:17 +0000267#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000268 /* On Unix, set the file system encoding according to the
269 user's preference, if the CODESET names a well-known
270 Python codec, and Py_FileSystemDefaultEncoding isn't
271 initialized by other means. Also set the encoding of
272 stdin and stdout if these are terminals. */
Martin v. Löwis011e8422009-05-05 04:43:17 +0000273
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000274 codeset = get_codeset();
275 if (codeset) {
276 if (!Py_FileSystemDefaultEncoding)
277 Py_FileSystemDefaultEncoding = codeset;
278 else
279 free(codeset);
280 }
Martin v. Löwis011e8422009-05-05 04:43:17 +0000281#endif
282
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000283 if (install_sigs)
284 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000285
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000286 /* Initialize warnings. */
287 _PyWarnings_Init();
288 if (PySys_HasWarnOptions()) {
289 PyObject *warnings_module = PyImport_ImportModule("warnings");
290 if (!warnings_module)
291 PyErr_Clear();
292 Py_XDECREF(warnings_module);
293 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000294
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000295 initmain(); /* Module __main__ */
296 if (initstdio() < 0)
297 Py_FatalError(
298 "Py_Initialize: can't initialize sys standard streams");
299
300 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000301#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000302 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000303#endif /* WITH_THREAD */
Victor Stinnerffbc2f62010-03-21 21:48:45 +0000304
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000305 if (!Py_NoSiteFlag)
306 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307}
308
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000309void
310Py_Initialize(void)
311{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000312 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000313}
314
315
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000316#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000317extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000318#endif
319
Guido van Rossume8432ac2007-07-09 15:04:50 +0000320/* Flush stdout and stderr */
321
Neal Norwitz2bad9702007-08-27 06:19:22 +0000322static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000323flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000324{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000325 PyObject *fout = PySys_GetObject("stdout");
326 PyObject *ferr = PySys_GetObject("stderr");
327 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000328
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000329 if (fout != NULL && fout != Py_None) {
330 tmp = PyObject_CallMethod(fout, "flush", "");
331 if (tmp == NULL)
332 PyErr_Clear();
333 else
334 Py_DECREF(tmp);
335 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000336
Victor Stinnerebb5a882010-05-14 01:03:14 +0000337 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000338 tmp = PyObject_CallMethod(ferr, "flush", "");
339 if (tmp == NULL)
340 PyErr_Clear();
341 else
342 Py_DECREF(tmp);
343 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000344}
345
Guido van Rossum25ce5661997-08-02 03:10:38 +0000346/* Undo the effect of Py_Initialize().
347
348 Beware: if multiple interpreter and/or thread states exist, these
349 are not wiped out; only the current thread and interpreter state
350 are deleted. But since everything else is deleted, those other
351 interpreter and thread states should no longer be used.
352
353 (XXX We should do better, e.g. wipe out all interpreters and
354 threads.)
355
356 Locking: as above.
357
358*/
359
360void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000361Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000363 PyInterpreterState *interp;
364 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000365
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000366 if (!initialized)
367 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000369 wait_for_thread_shutdown();
Antoine Pitroucefb3162009-10-20 22:08:36 +0000370
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000371 /* The interpreter is still entirely intact at this point, and the
372 * exit funcs may be relying on that. In particular, if some thread
373 * or exit func is still waiting to do an import, the import machinery
374 * expects Py_IsInitialized() to return true. So don't say the
375 * interpreter is uninitialized until after the exit funcs have run.
376 * Note that Threading.py uses an exit func to do a join on all the
377 * threads created thru it, so this also protects pending imports in
378 * the threads created via Threading.
379 */
380 call_py_exitfuncs();
381 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000382
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000383 /* Flush stdout+stderr */
384 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000385
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000386 /* Get current thread state and interpreter pointer */
387 tstate = PyThreadState_GET();
388 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000389
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000390 /* Disable signal handling */
391 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000392
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000393 /* Clear type lookup cache */
394 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000395
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000396 /* Collect garbage. This may call finalizers; it's nice to call these
397 * before all modules are destroyed.
398 * XXX If a __del__ or weakref callback is triggered here, and tries to
399 * XXX import a module, bad things can happen, because Python no
400 * XXX longer believes it's initialized.
401 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
402 * XXX is easy to provoke that way. I've also seen, e.g.,
403 * XXX Exception exceptions.ImportError: 'No module named sha'
404 * XXX in <function callback at 0x008F5718> ignored
405 * XXX but I'm unclear on exactly how that one happens. In any case,
406 * XXX I haven't seen a real-life report of either of these.
407 */
408 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000409#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000410 /* With COUNT_ALLOCS, it helps to run GC multiple times:
411 each collection might release some types from the type
412 list, so they become garbage. */
413 while (PyGC_Collect() > 0)
414 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000415#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000416
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000417 /* Destroy all modules */
418 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000419
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000420 /* Flush stdout+stderr (again, in case more was printed) */
421 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000422
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000423 /* Collect final garbage. This disposes of cycles created by
424 * new-style class definitions, for example.
425 * XXX This is disabled because it caused too many problems. If
426 * XXX a __del__ or weakref callback triggers here, Python code has
427 * XXX a hard time running, because even the sys module has been
428 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
429 * XXX One symptom is a sequence of information-free messages
430 * XXX coming from threads (if a __del__ or callback is invoked,
431 * XXX other threads can execute too, and any exception they encounter
432 * XXX triggers a comedy of errors as subsystem after subsystem
433 * XXX fails to find what it *expects* to find in sys to help report
434 * XXX the exception and consequent unexpected failures). I've also
435 * XXX seen segfaults then, after adding print statements to the
436 * XXX Python code getting called.
437 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000438#if 0
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000439 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000440#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000441
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000442 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
443 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000444
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000445 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000446#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000447 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000448#endif
449
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000450 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000451
Tim Peters9cf25ce2003-04-17 15:21:01 +0000452#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000453 /* Display all objects still alive -- this can invoke arbitrary
454 * __repr__ overrides, so requires a mostly-intact interpreter.
455 * Alas, a lot of stuff may still be alive now that will be cleaned
456 * up later.
457 */
458 if (Py_GETENV("PYTHONDUMPREFS"))
459 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000460#endif /* Py_TRACE_REFS */
461
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000462 /* Clear interpreter state */
463 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000464
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000465 /* Now we decref the exception classes. After this point nothing
466 can raise an exception. That's okay, because each Fini() method
467 below has been checked to make sure no exceptions are ever
468 raised.
469 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000470
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000471 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000472
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000473 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000474#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000475 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000476#endif /* WITH_THREAD */
477
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000478 /* Delete current thread */
479 PyThreadState_Swap(NULL);
480 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000481
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000482 /* Sundry finalizers */
483 PyMethod_Fini();
484 PyFrame_Fini();
485 PyCFunction_Fini();
486 PyTuple_Fini();
487 PyList_Fini();
488 PySet_Fini();
489 PyBytes_Fini();
490 PyByteArray_Fini();
491 PyLong_Fini();
492 PyFloat_Fini();
493 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000494
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000495 /* Cleanup Unicode implementation */
496 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000497
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000498 /* reset file system default encoding */
499 if (!Py_HasFileSystemDefaultEncoding) {
500 free((char*)Py_FileSystemDefaultEncoding);
501 Py_FileSystemDefaultEncoding = NULL;
502 }
Christian Heimesc8967002007-11-30 10:18:26 +0000503
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000504 /* XXX Still allocated:
505 - various static ad-hoc pointers to interned strings
506 - int and float free list blocks
507 - whatever various modules and libraries allocate
508 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000509
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000510 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000511
Tim Peters269b2a62003-04-17 19:52:29 +0000512#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000513 /* Display addresses (& refcnts) of all objects still alive.
514 * An address can be used to find the repr of the object, printed
515 * above by _Py_PrintReferences.
516 */
517 if (Py_GETENV("PYTHONDUMPREFS"))
518 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000519#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000520#ifdef PYMALLOC_DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000521 if (Py_GETENV("PYTHONMALLOCSTATS"))
522 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000523#endif
524
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000525 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000526}
527
528/* Create and initialize a new interpreter and thread, and return the
529 new thread. This requires that Py_Initialize() has been called
530 first.
531
532 Unsuccessful initialization yields a NULL pointer. Note that *no*
533 exception information is available even in this case -- the
534 exception information is held in the thread, and there is no
535 thread.
536
537 Locking: as above.
538
539*/
540
541PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000542Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000543{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000544 PyInterpreterState *interp;
545 PyThreadState *tstate, *save_tstate;
546 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000547
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000548 if (!initialized)
549 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000550
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000551 interp = PyInterpreterState_New();
552 if (interp == NULL)
553 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000554
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000555 tstate = PyThreadState_New(interp);
556 if (tstate == NULL) {
557 PyInterpreterState_Delete(interp);
558 return NULL;
559 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000561 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000563 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000565 interp->modules = PyDict_New();
566 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000568 bimod = _PyImport_FindExtension("builtins", "builtins");
569 if (bimod != NULL) {
570 interp->builtins = PyModule_GetDict(bimod);
571 if (interp->builtins == NULL)
572 goto handle_error;
573 Py_INCREF(interp->builtins);
574 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000575
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000576 /* initialize builtin exceptions */
577 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000578
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000579 sysmod = _PyImport_FindExtension("sys", "sys");
580 if (bimod != NULL && sysmod != NULL) {
581 PyObject *pstderr;
582 interp->sysdict = PyModule_GetDict(sysmod);
583 if (interp->sysdict == NULL)
584 goto handle_error;
585 Py_INCREF(interp->sysdict);
586 PySys_SetPath(Py_GetPath());
587 PyDict_SetItemString(interp->sysdict, "modules",
588 interp->modules);
589 /* Set up a preliminary stderr printer until we have enough
590 infrastructure for the io module in place. */
591 pstderr = PyFile_NewStdPrinter(fileno(stderr));
592 if (pstderr == NULL)
593 Py_FatalError("Py_Initialize: can't set preliminary stderr");
594 PySys_SetObject("stderr", pstderr);
595 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000596
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000597 _PyImportHooks_Init();
598 if (initstdio() < 0)
599 Py_FatalError(
600 "Py_Initialize: can't initialize sys standard streams");
601 initmain();
602 if (!Py_NoSiteFlag)
603 initsite();
604 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000605
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000606 if (!PyErr_Occurred())
607 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608
Thomas Wouters89f507f2006-12-13 04:49:30 +0000609handle_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000610 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000611
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000612 PyErr_Print();
613 PyThreadState_Clear(tstate);
614 PyThreadState_Swap(save_tstate);
615 PyThreadState_Delete(tstate);
616 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000618 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000619}
620
621/* Delete an interpreter and its last thread. This requires that the
622 given thread state is current, that the thread has no remaining
623 frames, and that it is its interpreter's only remaining thread.
624 It is a fatal error to violate these constraints.
625
626 (Py_Finalize() doesn't have these constraints -- it zaps
627 everything, regardless.)
628
629 Locking: as above.
630
631*/
632
633void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000634Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000636 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000638 if (tstate != PyThreadState_GET())
639 Py_FatalError("Py_EndInterpreter: thread is not current");
640 if (tstate->frame != NULL)
641 Py_FatalError("Py_EndInterpreter: thread still has a frame");
642 if (tstate != interp->tstate_head || tstate->next != NULL)
643 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000645 PyImport_Cleanup();
646 PyInterpreterState_Clear(interp);
647 PyThreadState_Swap(NULL);
648 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000649}
650
Martin v. Löwis790465f2008-04-05 20:41:37 +0000651static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000652
653void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000654Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000655{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000656 if (pn && *pn)
657 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000658}
659
Martin v. Löwis790465f2008-04-05 20:41:37 +0000660wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000661Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000662{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000663 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000664}
665
Martin v. Löwis790465f2008-04-05 20:41:37 +0000666static wchar_t *default_home = NULL;
667static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000668
669void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000670Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000671{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000672 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000673}
674
Martin v. Löwis790465f2008-04-05 20:41:37 +0000675wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000676Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000677{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000678 wchar_t *home = default_home;
679 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
680 char* chome = Py_GETENV("PYTHONHOME");
681 if (chome) {
682 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
683 if (r != (size_t)-1 && r <= PATH_MAX)
684 home = env_home;
685 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000686
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000687 }
688 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000689}
690
Guido van Rossum6135a871995-01-09 17:53:26 +0000691/* Create __main__ module */
692
693static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000694initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000695{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000696 PyObject *m, *d;
697 m = PyImport_AddModule("__main__");
698 if (m == NULL)
699 Py_FatalError("can't create __main__ module");
700 d = PyModule_GetDict(m);
701 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
702 PyObject *bimod = PyImport_ImportModule("builtins");
703 if (bimod == NULL ||
704 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
705 Py_FatalError("can't add __builtins__ to __main__");
706 Py_DECREF(bimod);
707 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000708}
709
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000710/* Import the site module (not into __main__ though) */
711
712static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000713initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000714{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000715 PyObject *m, *f;
716 m = PyImport_ImportModule("site");
717 if (m == NULL) {
718 f = PySys_GetObject("stderr");
719 if (f == NULL || f == Py_None)
720 return;
721 if (Py_VerboseFlag) {
722 PyFile_WriteString(
723 "'import site' failed; traceback:\n", f);
724 PyErr_Print();
725 }
726 else {
727 PyFile_WriteString(
728 "'import site' failed; use -v for traceback\n", f);
729 PyErr_Clear();
730 }
731 }
732 else {
733 Py_DECREF(m);
734 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000735}
736
Antoine Pitrou05608432009-01-09 18:53:14 +0000737static PyObject*
738create_stdio(PyObject* io,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000739 int fd, int write_mode, char* name,
740 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000741{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000742 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
743 const char* mode;
744 PyObject *line_buffering;
745 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000746
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000747 /* stdin is always opened in buffered mode, first because it shouldn't
748 make a difference in common use cases, second because TextIOWrapper
749 depends on the presence of a read1() method which only exists on
750 buffered streams.
751 */
752 if (Py_UnbufferedStdioFlag && write_mode)
753 buffering = 0;
754 else
755 buffering = -1;
756 if (write_mode)
757 mode = "wb";
758 else
759 mode = "rb";
760 buf = PyObject_CallMethod(io, "open", "isiOOOi",
761 fd, mode, buffering,
762 Py_None, Py_None, Py_None, 0);
763 if (buf == NULL)
764 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000765
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000766 if (buffering) {
767 raw = PyObject_GetAttrString(buf, "raw");
768 if (raw == NULL)
769 goto error;
770 }
771 else {
772 raw = buf;
773 Py_INCREF(raw);
774 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000775
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000776 text = PyUnicode_FromString(name);
777 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
778 goto error;
779 res = PyObject_CallMethod(raw, "isatty", "");
780 if (res == NULL)
781 goto error;
782 isatty = PyObject_IsTrue(res);
783 Py_DECREF(res);
784 if (isatty == -1)
785 goto error;
786 if (isatty || Py_UnbufferedStdioFlag)
787 line_buffering = Py_True;
788 else
789 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000790
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000791 Py_CLEAR(raw);
792 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000793
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000794 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
795 buf, encoding, errors,
796 "\n", line_buffering);
797 Py_CLEAR(buf);
798 if (stream == NULL)
799 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000800
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000801 if (write_mode)
802 mode = "w";
803 else
804 mode = "r";
805 text = PyUnicode_FromString(mode);
806 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
807 goto error;
808 Py_CLEAR(text);
809 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000810
811error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000812 Py_XDECREF(buf);
813 Py_XDECREF(stream);
814 Py_XDECREF(text);
815 Py_XDECREF(raw);
816 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000817}
818
Georg Brandl1a3284e2007-12-02 09:40:06 +0000819/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000820static int
821initstdio(void)
822{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000823 PyObject *iomod = NULL, *wrapper;
824 PyObject *bimod = NULL;
825 PyObject *m;
826 PyObject *std = NULL;
827 int status = 0, fd;
828 PyObject * encoding_attr;
829 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000830
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000831 /* Hack to avoid a nasty recursion issue when Python is invoked
832 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
833 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
834 goto error;
835 }
836 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000837
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000838 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
839 goto error;
840 }
841 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000842
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000843 if (!(bimod = PyImport_ImportModule("builtins"))) {
844 goto error;
845 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000846
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000847 if (!(iomod = PyImport_ImportModule("io"))) {
848 goto error;
849 }
850 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
851 goto error;
852 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000853
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000854 /* Set builtins.open */
855 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
856 goto error;
857 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000858
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000859 encoding = Py_GETENV("PYTHONIOENCODING");
860 errors = NULL;
861 if (encoding) {
862 encoding = strdup(encoding);
863 errors = strchr(encoding, ':');
864 if (errors) {
865 *errors = '\0';
866 errors++;
867 }
868 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000869
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000870 /* Set sys.stdin */
871 fd = fileno(stdin);
872 /* Under some conditions stdin, stdout and stderr may not be connected
873 * and fileno() may point to an invalid file descriptor. For example
874 * GUI apps don't have valid standard streams by default.
875 */
876 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000877#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000878 std = Py_None;
879 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000880#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000881 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000882#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000883 }
884 else {
885 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
886 if (std == NULL)
887 goto error;
888 } /* if (fd < 0) */
889 PySys_SetObject("__stdin__", std);
890 PySys_SetObject("stdin", std);
891 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000892
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000893 /* Set sys.stdout */
894 fd = fileno(stdout);
895 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000896#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000897 std = Py_None;
898 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000899#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000900 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000901#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000902 }
903 else {
904 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
905 if (std == NULL)
906 goto error;
907 } /* if (fd < 0) */
908 PySys_SetObject("__stdout__", std);
909 PySys_SetObject("stdout", std);
910 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000911
Guido van Rossum98297ee2007-11-06 21:34:58 +0000912#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000913 /* Set sys.stderr, replaces the preliminary stderr */
914 fd = fileno(stderr);
915 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000916#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000917 std = Py_None;
918 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000919#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000920 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000921#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000922 }
923 else {
924 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
925 if (std == NULL)
926 goto error;
927 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000928
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000929 /* Same as hack above, pre-import stderr's codec to avoid recursion
930 when import.c tries to write to stderr in verbose mode. */
931 encoding_attr = PyObject_GetAttrString(std, "encoding");
932 if (encoding_attr != NULL) {
933 const char * encoding;
934 encoding = _PyUnicode_AsString(encoding_attr);
935 if (encoding != NULL) {
936 _PyCodec_Lookup(encoding);
937 }
938 }
939 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000940
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000941 PySys_SetObject("__stderr__", std);
942 PySys_SetObject("stderr", std);
943 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000944#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000945
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000946 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000947 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000948 status = -1;
949 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000950
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000951 if (encoding)
952 free(encoding);
953 Py_XDECREF(bimod);
954 Py_XDECREF(iomod);
955 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000956}
957
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000958/* Parse input from a file and execute it */
959
960int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000961PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000962 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000963{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000964 if (filename == NULL)
965 filename = "???";
966 if (Py_FdIsInteractive(fp, filename)) {
967 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
968 if (closeit)
969 fclose(fp);
970 return err;
971 }
972 else
973 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000974}
975
976int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000977PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000978{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000979 PyObject *v;
980 int ret;
981 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000982
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000983 if (flags == NULL) {
984 flags = &local_flags;
985 local_flags.cf_flags = 0;
986 }
987 v = PySys_GetObject("ps1");
988 if (v == NULL) {
989 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
990 Py_XDECREF(v);
991 }
992 v = PySys_GetObject("ps2");
993 if (v == NULL) {
994 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
995 Py_XDECREF(v);
996 }
997 for (;;) {
998 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
999 PRINT_TOTAL_REFS();
1000 if (ret == E_EOF)
1001 return 0;
1002 /*
1003 if (ret == E_NOMEM)
1004 return -1;
1005 */
1006 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001007}
1008
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001009/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001010static int PARSER_FLAGS(PyCompilerFlags *flags)
1011{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001012 int parser_flags = 0;
1013 if (!flags)
1014 return 0;
1015 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1016 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1017 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1018 parser_flags |= PyPARSE_IGNORE_COOKIE;
1019 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1020 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1021 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001022}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001023
Thomas Wouters89f507f2006-12-13 04:49:30 +00001024#if 0
1025/* Keep an example of flags with future keyword support. */
1026#define PARSER_FLAGS(flags) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001027 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1028 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1029 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1030 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001031#endif
1032
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001033int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001034PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001035{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001036 PyObject *m, *d, *v, *w, *oenc = NULL;
1037 mod_ty mod;
1038 PyArena *arena;
1039 char *ps1 = "", *ps2 = "", *enc = NULL;
1040 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001041
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001042 if (fp == stdin) {
1043 /* Fetch encoding from sys.stdin */
1044 v = PySys_GetObject("stdin");
1045 if (v == NULL || v == Py_None)
1046 return -1;
1047 oenc = PyObject_GetAttrString(v, "encoding");
1048 if (!oenc)
1049 return -1;
1050 enc = _PyUnicode_AsString(oenc);
1051 }
1052 v = PySys_GetObject("ps1");
1053 if (v != NULL) {
1054 v = PyObject_Str(v);
1055 if (v == NULL)
1056 PyErr_Clear();
1057 else if (PyUnicode_Check(v))
1058 ps1 = _PyUnicode_AsString(v);
1059 }
1060 w = PySys_GetObject("ps2");
1061 if (w != NULL) {
1062 w = PyObject_Str(w);
1063 if (w == NULL)
1064 PyErr_Clear();
1065 else if (PyUnicode_Check(w))
1066 ps2 = _PyUnicode_AsString(w);
1067 }
1068 arena = PyArena_New();
1069 if (arena == NULL) {
1070 Py_XDECREF(v);
1071 Py_XDECREF(w);
1072 Py_XDECREF(oenc);
1073 return -1;
1074 }
1075 mod = PyParser_ASTFromFile(fp, filename, enc,
1076 Py_single_input, ps1, ps2,
1077 flags, &errcode, arena);
1078 Py_XDECREF(v);
1079 Py_XDECREF(w);
1080 Py_XDECREF(oenc);
1081 if (mod == NULL) {
1082 PyArena_Free(arena);
1083 if (errcode == E_EOF) {
1084 PyErr_Clear();
1085 return E_EOF;
1086 }
1087 PyErr_Print();
1088 return -1;
1089 }
1090 m = PyImport_AddModule("__main__");
1091 if (m == NULL) {
1092 PyArena_Free(arena);
1093 return -1;
1094 }
1095 d = PyModule_GetDict(m);
1096 v = run_mod(mod, filename, d, d, flags, arena);
1097 PyArena_Free(arena);
1098 flush_io();
1099 if (v == NULL) {
1100 PyErr_Print();
1101 return -1;
1102 }
1103 Py_DECREF(v);
1104 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001105}
1106
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001107/* Check whether a file maybe a pyc file: Look at the extension,
1108 the file type, and, if we may close it, at the first few bytes. */
1109
1110static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001111maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001112{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001113 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1114 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001115
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001116 /* Only look into the file if we are allowed to close it, since
1117 it then should also be seekable. */
1118 if (closeit) {
1119 /* Read only two bytes of the magic. If the file was opened in
1120 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1121 be read as they are on disk. */
1122 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1123 unsigned char buf[2];
1124 /* Mess: In case of -x, the stream is NOT at its start now,
1125 and ungetc() was used to push back the first newline,
1126 which makes the current stream position formally undefined,
1127 and a x-platform nightmare.
1128 Unfortunately, we have no direct way to know whether -x
1129 was specified. So we use a terrible hack: if the current
1130 stream position is not 0, we assume -x was specified, and
1131 give up. Bug 132850 on SourceForge spells out the
1132 hopelessness of trying anything else (fseek and ftell
1133 don't work predictably x-platform for text-mode files).
1134 */
1135 int ispyc = 0;
1136 if (ftell(fp) == 0) {
1137 if (fread(buf, 1, 2, fp) == 2 &&
1138 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1139 ispyc = 1;
1140 rewind(fp);
1141 }
1142 return ispyc;
1143 }
1144 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001145}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001146
Guido van Rossum0df002c2000-08-27 19:21:52 +00001147int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001148PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001149 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001150{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001151 PyObject *m, *d, *v;
1152 const char *ext;
1153 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001154
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001155 m = PyImport_AddModule("__main__");
1156 if (m == NULL)
1157 return -1;
1158 d = PyModule_GetDict(m);
1159 if (PyDict_GetItemString(d, "__file__") == NULL) {
1160 PyObject *f;
1161 f = PyUnicode_DecodeFSDefault(filename);
1162 if (f == NULL)
1163 return -1;
1164 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1165 Py_DECREF(f);
1166 return -1;
1167 }
1168 set_file_name = 1;
1169 Py_DECREF(f);
1170 }
1171 len = strlen(filename);
1172 ext = filename + len - (len > 4 ? 4 : 0);
1173 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1174 /* Try to run a pyc file. First, re-open in binary */
1175 if (closeit)
1176 fclose(fp);
1177 if ((fp = fopen(filename, "rb")) == NULL) {
1178 fprintf(stderr, "python: Can't reopen .pyc file\n");
1179 ret = -1;
1180 goto done;
1181 }
1182 /* Turn on optimization if a .pyo file is given */
1183 if (strcmp(ext, ".pyo") == 0)
1184 Py_OptimizeFlag = 1;
1185 v = run_pyc_file(fp, filename, d, d, flags);
1186 } else {
1187 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1188 closeit, flags);
1189 }
1190 flush_io();
1191 if (v == NULL) {
1192 PyErr_Print();
1193 ret = -1;
1194 goto done;
1195 }
1196 Py_DECREF(v);
1197 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001198 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001199 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1200 PyErr_Clear();
1201 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001202}
1203
1204int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001205PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001206{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001207 PyObject *m, *d, *v;
1208 m = PyImport_AddModule("__main__");
1209 if (m == NULL)
1210 return -1;
1211 d = PyModule_GetDict(m);
1212 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1213 if (v == NULL) {
1214 PyErr_Print();
1215 return -1;
1216 }
1217 Py_DECREF(v);
1218 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001219}
1220
Barry Warsaw035574d1997-08-29 22:07:17 +00001221static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001222parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001223 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001224{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001225 long hold;
1226 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001227
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001228 /* old style errors */
1229 if (PyTuple_Check(err))
1230 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1231 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001232
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001233 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001234
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001235 if (! (v = PyObject_GetAttrString(err, "msg")))
1236 goto finally;
1237 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001238
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001239 if (!(v = PyObject_GetAttrString(err, "filename")))
1240 goto finally;
1241 if (v == Py_None)
1242 *filename = NULL;
1243 else if (! (*filename = _PyUnicode_AsString(v)))
1244 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001245
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001246 Py_DECREF(v);
1247 if (!(v = PyObject_GetAttrString(err, "lineno")))
1248 goto finally;
1249 hold = PyLong_AsLong(v);
1250 Py_DECREF(v);
1251 v = NULL;
1252 if (hold < 0 && PyErr_Occurred())
1253 goto finally;
1254 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001255
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001256 if (!(v = PyObject_GetAttrString(err, "offset")))
1257 goto finally;
1258 if (v == Py_None) {
1259 *offset = -1;
1260 Py_DECREF(v);
1261 v = NULL;
1262 } else {
1263 hold = PyLong_AsLong(v);
1264 Py_DECREF(v);
1265 v = NULL;
1266 if (hold < 0 && PyErr_Occurred())
1267 goto finally;
1268 *offset = (int)hold;
1269 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001270
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001271 if (!(v = PyObject_GetAttrString(err, "text")))
1272 goto finally;
1273 if (v == Py_None)
1274 *text = NULL;
1275 else if (!PyUnicode_Check(v) ||
1276 !(*text = _PyUnicode_AsString(v)))
1277 goto finally;
1278 Py_DECREF(v);
1279 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001280
1281finally:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001282 Py_XDECREF(v);
1283 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001284}
1285
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001286void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001287PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001288{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001289 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001290}
1291
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001292static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001293print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001294{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001295 char *nl;
1296 if (offset >= 0) {
1297 if (offset > 0 && offset == (int)strlen(text))
1298 offset--;
1299 for (;;) {
1300 nl = strchr(text, '\n');
1301 if (nl == NULL || nl-text >= offset)
1302 break;
1303 offset -= (int)(nl+1-text);
1304 text = nl+1;
1305 }
1306 while (*text == ' ' || *text == '\t') {
1307 text++;
1308 offset--;
1309 }
1310 }
1311 PyFile_WriteString(" ", f);
1312 PyFile_WriteString(text, f);
1313 if (*text == '\0' || text[strlen(text)-1] != '\n')
1314 PyFile_WriteString("\n", f);
1315 if (offset == -1)
1316 return;
1317 PyFile_WriteString(" ", f);
1318 offset--;
1319 while (offset > 0) {
1320 PyFile_WriteString(" ", f);
1321 offset--;
1322 }
1323 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001324}
1325
Guido van Rossum66e8e862001-03-23 17:54:43 +00001326static void
1327handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001328{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001329 PyObject *exception, *value, *tb;
1330 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001331
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001332 if (Py_InspectFlag)
1333 /* Don't exit if -i flag was given. This flag is set to 0
1334 * when entering interactive mode for inspecting. */
1335 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001336
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001337 PyErr_Fetch(&exception, &value, &tb);
1338 fflush(stdout);
1339 if (value == NULL || value == Py_None)
1340 goto done;
1341 if (PyExceptionInstance_Check(value)) {
1342 /* The error code should be in the `code' attribute. */
1343 PyObject *code = PyObject_GetAttrString(value, "code");
1344 if (code) {
1345 Py_DECREF(value);
1346 value = code;
1347 if (value == Py_None)
1348 goto done;
1349 }
1350 /* If we failed to dig out the 'code' attribute,
1351 just let the else clause below print the error. */
1352 }
1353 if (PyLong_Check(value))
1354 exitcode = (int)PyLong_AsLong(value);
1355 else {
Victor Stinner2e71d012010-05-17 09:35:44 +00001356 PyObject *sys_stderr = PySys_GetObject("stderr");
1357 if (sys_stderr != NULL)
1358 PyObject_CallMethod(sys_stderr, "flush", NULL);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001359 PyObject_Print(value, stderr, Py_PRINT_RAW);
Victor Stinner2e71d012010-05-17 09:35:44 +00001360 fflush(stderr);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001361 PySys_WriteStderr("\n");
1362 exitcode = 1;
1363 }
Tim Peterscf615b52003-04-19 18:47:02 +00001364 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001365 /* Restore and clear the exception info, in order to properly decref
1366 * the exception, value, and traceback. If we just exit instead,
1367 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1368 * some finalizers from running.
1369 */
1370 PyErr_Restore(exception, value, tb);
1371 PyErr_Clear();
1372 Py_Exit(exitcode);
1373 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001374}
1375
1376void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001377PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001378{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001379 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001380
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001381 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1382 handle_system_exit();
1383 }
1384 PyErr_Fetch(&exception, &v, &tb);
1385 if (exception == NULL)
1386 return;
1387 PyErr_NormalizeException(&exception, &v, &tb);
1388 if (tb == NULL) {
1389 tb = Py_None;
1390 Py_INCREF(tb);
1391 }
1392 PyException_SetTraceback(v, tb);
1393 if (exception == NULL)
1394 return;
1395 /* Now we know v != NULL too */
1396 if (set_sys_last_vars) {
1397 PySys_SetObject("last_type", exception);
1398 PySys_SetObject("last_value", v);
1399 PySys_SetObject("last_traceback", tb);
1400 }
1401 hook = PySys_GetObject("excepthook");
1402 if (hook) {
1403 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1404 PyObject *result = PyEval_CallObject(hook, args);
1405 if (result == NULL) {
1406 PyObject *exception2, *v2, *tb2;
1407 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1408 handle_system_exit();
1409 }
1410 PyErr_Fetch(&exception2, &v2, &tb2);
1411 PyErr_NormalizeException(&exception2, &v2, &tb2);
1412 /* It should not be possible for exception2 or v2
1413 to be NULL. However PyErr_Display() can't
1414 tolerate NULLs, so just be safe. */
1415 if (exception2 == NULL) {
1416 exception2 = Py_None;
1417 Py_INCREF(exception2);
1418 }
1419 if (v2 == NULL) {
1420 v2 = Py_None;
1421 Py_INCREF(v2);
1422 }
1423 fflush(stdout);
1424 PySys_WriteStderr("Error in sys.excepthook:\n");
1425 PyErr_Display(exception2, v2, tb2);
1426 PySys_WriteStderr("\nOriginal exception was:\n");
1427 PyErr_Display(exception, v, tb);
1428 Py_DECREF(exception2);
1429 Py_DECREF(v2);
1430 Py_XDECREF(tb2);
1431 }
1432 Py_XDECREF(result);
1433 Py_XDECREF(args);
1434 } else {
1435 PySys_WriteStderr("sys.excepthook is missing\n");
1436 PyErr_Display(exception, v, tb);
1437 }
1438 Py_XDECREF(exception);
1439 Py_XDECREF(v);
1440 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001441}
1442
Benjamin Petersone6528212008-07-15 15:32:09 +00001443static void
1444print_exception(PyObject *f, PyObject *value)
1445{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001446 int err = 0;
1447 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001448
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001449 if (!PyExceptionInstance_Check(value)) {
1450 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1451 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1452 PyFile_WriteString(" found\n", f);
1453 return;
1454 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001455
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001456 Py_INCREF(value);
1457 fflush(stdout);
1458 type = (PyObject *) Py_TYPE(value);
1459 tb = PyException_GetTraceback(value);
1460 if (tb && tb != Py_None)
1461 err = PyTraceBack_Print(tb, f);
1462 if (err == 0 &&
1463 PyObject_HasAttrString(value, "print_file_and_line"))
1464 {
1465 PyObject *message;
1466 const char *filename, *text;
1467 int lineno, offset;
1468 if (!parse_syntax_error(value, &message, &filename,
1469 &lineno, &offset, &text))
1470 PyErr_Clear();
1471 else {
1472 char buf[10];
1473 PyFile_WriteString(" File \"", f);
1474 if (filename == NULL)
1475 PyFile_WriteString("<string>", f);
1476 else
1477 PyFile_WriteString(filename, f);
1478 PyFile_WriteString("\", line ", f);
1479 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1480 PyFile_WriteString(buf, f);
1481 PyFile_WriteString("\n", f);
1482 if (text != NULL)
1483 print_error_text(f, offset, text);
1484 Py_DECREF(value);
1485 value = message;
1486 /* Can't be bothered to check all those
1487 PyFile_WriteString() calls */
1488 if (PyErr_Occurred())
1489 err = -1;
1490 }
1491 }
1492 if (err) {
1493 /* Don't do anything else */
1494 }
1495 else {
1496 PyObject* moduleName;
1497 char* className;
1498 assert(PyExceptionClass_Check(type));
1499 className = PyExceptionClass_Name(type);
1500 if (className != NULL) {
1501 char *dot = strrchr(className, '.');
1502 if (dot != NULL)
1503 className = dot+1;
1504 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001505
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001506 moduleName = PyObject_GetAttrString(type, "__module__");
1507 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1508 {
1509 Py_DECREF(moduleName);
1510 err = PyFile_WriteString("<unknown>", f);
1511 }
1512 else {
1513 char* modstr = _PyUnicode_AsString(moduleName);
1514 if (modstr && strcmp(modstr, "builtins"))
1515 {
1516 err = PyFile_WriteString(modstr, f);
1517 err += PyFile_WriteString(".", f);
1518 }
1519 Py_DECREF(moduleName);
1520 }
1521 if (err == 0) {
1522 if (className == NULL)
1523 err = PyFile_WriteString("<unknown>", f);
1524 else
1525 err = PyFile_WriteString(className, f);
1526 }
1527 }
1528 if (err == 0 && (value != Py_None)) {
1529 PyObject *s = PyObject_Str(value);
1530 /* only print colon if the str() of the
1531 object is not the empty string
1532 */
1533 if (s == NULL)
1534 err = -1;
1535 else if (!PyUnicode_Check(s) ||
1536 PyUnicode_GetSize(s) != 0)
1537 err = PyFile_WriteString(": ", f);
1538 if (err == 0)
1539 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1540 Py_XDECREF(s);
1541 }
1542 /* try to write a newline in any case */
1543 err += PyFile_WriteString("\n", f);
1544 Py_XDECREF(tb);
1545 Py_DECREF(value);
1546 /* If an error happened here, don't show it.
1547 XXX This is wrong, but too many callers rely on this behavior. */
1548 if (err != 0)
1549 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001550}
1551
1552static const char *cause_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001553 "\nThe above exception was the direct cause "
1554 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001555
1556static const char *context_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001557 "\nDuring handling of the above exception, "
1558 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001559
1560static void
1561print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1562{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001563 int err = 0, res;
1564 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001565
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001566 if (seen != NULL) {
1567 /* Exception chaining */
1568 if (PySet_Add(seen, value) == -1)
1569 PyErr_Clear();
1570 else if (PyExceptionInstance_Check(value)) {
1571 cause = PyException_GetCause(value);
1572 context = PyException_GetContext(value);
1573 if (cause) {
1574 res = PySet_Contains(seen, cause);
1575 if (res == -1)
1576 PyErr_Clear();
1577 if (res == 0) {
1578 print_exception_recursive(
1579 f, cause, seen);
1580 err |= PyFile_WriteString(
1581 cause_message, f);
1582 }
1583 }
1584 else if (context) {
1585 res = PySet_Contains(seen, context);
1586 if (res == -1)
1587 PyErr_Clear();
1588 if (res == 0) {
1589 print_exception_recursive(
1590 f, context, seen);
1591 err |= PyFile_WriteString(
1592 context_message, f);
1593 }
1594 }
1595 Py_XDECREF(context);
1596 Py_XDECREF(cause);
1597 }
1598 }
1599 print_exception(f, value);
1600 if (err != 0)
1601 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001602}
1603
Thomas Wouters477c8d52006-05-27 19:21:47 +00001604void
1605PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001606{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001607 PyObject *seen;
1608 PyObject *f = PySys_GetObject("stderr");
1609 if (f == Py_None) {
1610 /* pass */
1611 }
1612 else if (f == NULL) {
1613 _PyObject_Dump(value);
1614 fprintf(stderr, "lost sys.stderr\n");
1615 }
1616 else {
1617 /* We choose to ignore seen being possibly NULL, and report
1618 at least the main exception (it could be a MemoryError).
1619 */
1620 seen = PySet_New(NULL);
1621 if (seen == NULL)
1622 PyErr_Clear();
1623 print_exception_recursive(f, value, seen);
1624 Py_XDECREF(seen);
1625 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001626}
1627
Guido van Rossum82598051997-03-05 00:20:32 +00001628PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001629PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001630 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001631{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001632 PyObject *ret = NULL;
1633 mod_ty mod;
1634 PyArena *arena = PyArena_New();
1635 if (arena == NULL)
1636 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001637
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001638 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1639 if (mod != NULL)
1640 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1641 PyArena_Free(arena);
1642 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001643}
1644
1645PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001646PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001647 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001648{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001649 PyObject *ret;
1650 mod_ty mod;
1651 PyArena *arena = PyArena_New();
1652 if (arena == NULL)
1653 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001654
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001655 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1656 flags, NULL, arena);
1657 if (closeit)
1658 fclose(fp);
1659 if (mod == NULL) {
1660 PyArena_Free(arena);
1661 return NULL;
1662 }
1663 ret = run_mod(mod, filename, globals, locals, flags, arena);
1664 PyArena_Free(arena);
1665 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001666}
1667
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001668static void
1669flush_io(void)
1670{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001671 PyObject *f, *r;
1672 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001673
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001674 /* Save the current exception */
1675 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001676
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001677 f = PySys_GetObject("stderr");
1678 if (f != NULL) {
1679 r = PyObject_CallMethod(f, "flush", "");
1680 if (r)
1681 Py_DECREF(r);
1682 else
1683 PyErr_Clear();
1684 }
1685 f = PySys_GetObject("stdout");
1686 if (f != NULL) {
1687 r = PyObject_CallMethod(f, "flush", "");
1688 if (r)
1689 Py_DECREF(r);
1690 else
1691 PyErr_Clear();
1692 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001693
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001694 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001695}
1696
Guido van Rossum82598051997-03-05 00:20:32 +00001697static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001698run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001699 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001700{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001701 PyCodeObject *co;
1702 PyObject *v;
1703 co = PyAST_Compile(mod, filename, flags, arena);
1704 if (co == NULL)
1705 return NULL;
1706 v = PyEval_EvalCode(co, globals, locals);
1707 Py_DECREF(co);
1708 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001709}
1710
Guido van Rossum82598051997-03-05 00:20:32 +00001711static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001712run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001713 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001714{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001715 PyCodeObject *co;
1716 PyObject *v;
1717 long magic;
1718 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001719
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001720 magic = PyMarshal_ReadLongFromFile(fp);
1721 if (magic != PyImport_GetMagicNumber()) {
1722 PyErr_SetString(PyExc_RuntimeError,
1723 "Bad magic number in .pyc file");
1724 return NULL;
1725 }
1726 (void) PyMarshal_ReadLongFromFile(fp);
1727 v = PyMarshal_ReadLastObjectFromFile(fp);
1728 fclose(fp);
1729 if (v == NULL || !PyCode_Check(v)) {
1730 Py_XDECREF(v);
1731 PyErr_SetString(PyExc_RuntimeError,
1732 "Bad code object in .pyc file");
1733 return NULL;
1734 }
1735 co = (PyCodeObject *)v;
1736 v = PyEval_EvalCode(co, globals, locals);
1737 if (v && flags)
1738 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1739 Py_DECREF(co);
1740 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001741}
1742
Guido van Rossum82598051997-03-05 00:20:32 +00001743PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001744Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001745 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001746{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001747 PyCodeObject *co;
1748 mod_ty mod;
1749 PyArena *arena = PyArena_New();
1750 if (arena == NULL)
1751 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001752
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001753 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1754 if (mod == NULL) {
1755 PyArena_Free(arena);
1756 return NULL;
1757 }
1758 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1759 PyObject *result = PyAST_mod2obj(mod);
1760 PyArena_Free(arena);
1761 return result;
1762 }
1763 co = PyAST_Compile(mod, filename, flags, arena);
1764 PyArena_Free(arena);
1765 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001766}
1767
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001768struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001769Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001770{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001771 struct symtable *st;
1772 mod_ty mod;
1773 PyCompilerFlags flags;
1774 PyArena *arena = PyArena_New();
1775 if (arena == NULL)
1776 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001777
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001778 flags.cf_flags = 0;
1779 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1780 if (mod == NULL) {
1781 PyArena_Free(arena);
1782 return NULL;
1783 }
1784 st = PySymtable_Build(mod, filename, 0);
1785 PyArena_Free(arena);
1786 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001787}
1788
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001789/* Preferred access to parser is through AST. */
1790mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001791PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001792 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001793{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001794 mod_ty mod;
1795 PyCompilerFlags localflags;
1796 perrdetail err;
1797 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001798
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001799 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1800 &_PyParser_Grammar, start, &err,
1801 &iflags);
1802 if (flags == NULL) {
1803 localflags.cf_flags = 0;
1804 flags = &localflags;
1805 }
1806 if (n) {
1807 flags->cf_flags |= iflags & PyCF_MASK;
1808 mod = PyAST_FromNode(n, flags, filename, arena);
1809 PyNode_Free(n);
1810 return mod;
1811 }
1812 else {
1813 err_input(&err);
1814 return NULL;
1815 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001816}
1817
1818mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001819PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001820 int start, char *ps1,
1821 char *ps2, PyCompilerFlags *flags, int *errcode,
1822 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001823{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001824 mod_ty mod;
1825 PyCompilerFlags localflags;
1826 perrdetail err;
1827 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001828
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001829 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1830 &_PyParser_Grammar,
1831 start, ps1, ps2, &err, &iflags);
1832 if (flags == NULL) {
1833 localflags.cf_flags = 0;
1834 flags = &localflags;
1835 }
1836 if (n) {
1837 flags->cf_flags |= iflags & PyCF_MASK;
1838 mod = PyAST_FromNode(n, flags, filename, arena);
1839 PyNode_Free(n);
1840 return mod;
1841 }
1842 else {
1843 err_input(&err);
1844 if (errcode)
1845 *errcode = err.error;
1846 return NULL;
1847 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001848}
1849
Guido van Rossuma110aa61994-08-29 12:50:44 +00001850/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001851
Guido van Rossuma110aa61994-08-29 12:50:44 +00001852node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001853PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001854{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001855 perrdetail err;
1856 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1857 &_PyParser_Grammar,
1858 start, NULL, NULL, &err, flags);
1859 if (n == NULL)
1860 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001861
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001862 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001863}
1864
Guido van Rossuma110aa61994-08-29 12:50:44 +00001865/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001866
Guido van Rossuma110aa61994-08-29 12:50:44 +00001867node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001868PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001869{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001870 perrdetail err;
1871 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1872 start, &err, flags);
1873 if (n == NULL)
1874 err_input(&err);
1875 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001876}
1877
1878node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001879PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001880 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001881{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001882 perrdetail err;
1883 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1884 &_PyParser_Grammar, start, &err, flags);
1885 if (n == NULL)
1886 err_input(&err);
1887 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001888}
1889
1890node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001891PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001892{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001893 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001894}
1895
Guido van Rossum66ebd912003-04-17 16:02:26 +00001896/* May want to move a more generalized form of this to parsetok.c or
1897 even parser modules. */
1898
1899void
1900PyParser_SetError(perrdetail *err)
1901{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001902 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001903}
1904
Guido van Rossuma110aa61994-08-29 12:50:44 +00001905/* Set the error appropriate to the given input error code (see errcode.h) */
1906
1907static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001908err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001909{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001910 PyObject *v, *w, *errtype, *errtext;
1911 PyObject* u = NULL;
1912 char *msg = NULL;
1913 errtype = PyExc_SyntaxError;
1914 switch (err->error) {
1915 case E_ERROR:
1916 return;
1917 case E_SYNTAX:
1918 errtype = PyExc_IndentationError;
1919 if (err->expected == INDENT)
1920 msg = "expected an indented block";
1921 else if (err->token == INDENT)
1922 msg = "unexpected indent";
1923 else if (err->token == DEDENT)
1924 msg = "unexpected unindent";
1925 else {
1926 errtype = PyExc_SyntaxError;
1927 msg = "invalid syntax";
1928 }
1929 break;
1930 case E_TOKEN:
1931 msg = "invalid token";
1932 break;
1933 case E_EOFS:
1934 msg = "EOF while scanning triple-quoted string literal";
1935 break;
1936 case E_EOLS:
1937 msg = "EOL while scanning string literal";
1938 break;
1939 case E_INTR:
1940 if (!PyErr_Occurred())
1941 PyErr_SetNone(PyExc_KeyboardInterrupt);
1942 goto cleanup;
1943 case E_NOMEM:
1944 PyErr_NoMemory();
1945 goto cleanup;
1946 case E_EOF:
1947 msg = "unexpected EOF while parsing";
1948 break;
1949 case E_TABSPACE:
1950 errtype = PyExc_TabError;
1951 msg = "inconsistent use of tabs and spaces in indentation";
1952 break;
1953 case E_OVERFLOW:
1954 msg = "expression too long";
1955 break;
1956 case E_DEDENT:
1957 errtype = PyExc_IndentationError;
1958 msg = "unindent does not match any outer indentation level";
1959 break;
1960 case E_TOODEEP:
1961 errtype = PyExc_IndentationError;
1962 msg = "too many levels of indentation";
1963 break;
1964 case E_DECODE: {
1965 PyObject *type, *value, *tb;
1966 PyErr_Fetch(&type, &value, &tb);
1967 if (value != NULL) {
1968 u = PyObject_Str(value);
1969 if (u != NULL) {
1970 msg = _PyUnicode_AsString(u);
1971 }
1972 }
1973 if (msg == NULL)
1974 msg = "unknown decode error";
1975 Py_XDECREF(type);
1976 Py_XDECREF(value);
1977 Py_XDECREF(tb);
1978 break;
1979 }
1980 case E_LINECONT:
1981 msg = "unexpected character after line continuation character";
1982 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001983
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001984 case E_IDENTIFIER:
1985 msg = "invalid character in identifier";
1986 break;
1987 default:
1988 fprintf(stderr, "error=%d\n", err->error);
1989 msg = "unknown parsing error";
1990 break;
1991 }
1992 /* err->text may not be UTF-8 in case of decoding errors.
1993 Explicitly convert to an object. */
1994 if (!err->text) {
1995 errtext = Py_None;
1996 Py_INCREF(Py_None);
1997 } else {
1998 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1999 "replace");
2000 }
2001 v = Py_BuildValue("(ziiN)", err->filename,
2002 err->lineno, err->offset, errtext);
2003 w = NULL;
2004 if (v != NULL)
2005 w = Py_BuildValue("(sO)", msg, v);
2006 Py_XDECREF(u);
2007 Py_XDECREF(v);
2008 PyErr_SetObject(errtype, w);
2009 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002010cleanup:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002011 if (err->text != NULL) {
2012 PyObject_FREE(err->text);
2013 err->text = NULL;
2014 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002015}
2016
2017/* Print fatal error message and abort */
2018
2019void
Tim Peters7c321a82002-07-09 02:57:01 +00002020Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002021{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002022 fprintf(stderr, "Fatal Python error: %s\n", msg);
2023 fflush(stderr); /* it helps in Windows debug build */
2024 if (PyErr_Occurred()) {
2025 PyErr_Print();
2026 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002027#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002028 {
2029 size_t len = strlen(msg);
2030 WCHAR* buffer;
2031 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002032
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002033 /* Convert the message to wchar_t. This uses a simple one-to-one
2034 conversion, assuming that the this error message actually uses ASCII
2035 only. If this ceases to be true, we will have to convert. */
2036 buffer = alloca( (len+1) * (sizeof *buffer));
2037 for( i=0; i<=len; ++i)
2038 buffer[i] = msg[i];
2039 OutputDebugStringW(L"Fatal Python error: ");
2040 OutputDebugStringW(buffer);
2041 OutputDebugStringW(L"\n");
2042 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002043#ifdef _DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002044 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002045#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002046#endif /* MS_WINDOWS */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002047 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002048}
2049
2050/* Clean up and exit */
2051
Guido van Rossuma110aa61994-08-29 12:50:44 +00002052#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002053#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002054#endif
2055
Collin Winter670e6922007-03-21 02:57:17 +00002056static void (*pyexitfunc)(void) = NULL;
2057/* For the atexit module. */
2058void _Py_PyAtExit(void (*func)(void))
2059{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002060 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002061}
2062
2063static void
2064call_py_exitfuncs(void)
2065{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002066 if (pyexitfunc == NULL)
2067 return;
Collin Winter670e6922007-03-21 02:57:17 +00002068
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002069 (*pyexitfunc)();
2070 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002071}
2072
Antoine Pitroucefb3162009-10-20 22:08:36 +00002073/* Wait until threading._shutdown completes, provided
2074 the threading module was imported in the first place.
2075 The shutdown routine will wait until all non-daemon
2076 "threading" threads have completed. */
2077static void
2078wait_for_thread_shutdown(void)
2079{
2080#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002081 PyObject *result;
2082 PyThreadState *tstate = PyThreadState_GET();
2083 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2084 "threading");
2085 if (threading == NULL) {
2086 /* threading not imported */
2087 PyErr_Clear();
2088 return;
2089 }
2090 result = PyObject_CallMethod(threading, "_shutdown", "");
2091 if (result == NULL) {
2092 PyErr_WriteUnraisable(threading);
2093 }
2094 else {
2095 Py_DECREF(result);
2096 }
2097 Py_DECREF(threading);
Antoine Pitroucefb3162009-10-20 22:08:36 +00002098#endif
2099}
2100
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002101#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002102static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002103static int nexitfuncs = 0;
2104
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002105int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002106{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002107 if (nexitfuncs >= NEXITFUNCS)
2108 return -1;
2109 exitfuncs[nexitfuncs++] = func;
2110 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002111}
2112
Guido van Rossumcc283f51997-08-05 02:22:03 +00002113static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002114call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002115{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002116 while (nexitfuncs > 0)
2117 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002118
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002119 fflush(stdout);
2120 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002121}
2122
2123void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002124Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002125{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002126 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002127
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002128 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002129}
2130
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002131static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002132initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002133{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002134#ifdef SIGPIPE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002135 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002136#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002137#ifdef SIGXFZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002138 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002139#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002140#ifdef SIGXFSZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002141 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002142#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002143 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002144}
2145
Guido van Rossum7433b121997-02-14 19:45:36 +00002146
2147/*
2148 * The file descriptor fd is considered ``interactive'' if either
2149 * a) isatty(fd) is TRUE, or
2150 * b) the -i flag was given, and the filename associated with
2151 * the descriptor is NULL or "<stdin>" or "???".
2152 */
2153int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002154Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002155{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002156 if (isatty((int)fileno(fp)))
2157 return 1;
2158 if (!Py_InteractiveFlag)
2159 return 0;
2160 return (filename == NULL) ||
2161 (strcmp(filename, "<stdin>") == 0) ||
2162 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002163}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002164
2165
Tim Petersd08e3822003-04-17 15:24:21 +00002166#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002167#if defined(WIN32) && defined(_MSC_VER)
2168
2169/* Stack checking for Microsoft C */
2170
2171#include <malloc.h>
2172#include <excpt.h>
2173
Fred Drakee8de31c2000-08-31 05:38:39 +00002174/*
2175 * Return non-zero when we run out of memory on the stack; zero otherwise.
2176 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002177int
Fred Drake399739f2000-08-31 05:52:44 +00002178PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002179{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002180 __try {
2181 /* alloca throws a stack overflow exception if there's
2182 not enough space left on the stack */
2183 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2184 return 0;
2185 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2186 EXCEPTION_EXECUTE_HANDLER :
2187 EXCEPTION_CONTINUE_SEARCH) {
2188 int errcode = _resetstkoflw();
2189 if (errcode == 0)
2190 {
2191 Py_FatalError("Could not reset the stack!");
2192 }
2193 }
2194 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002195}
2196
2197#endif /* WIN32 && _MSC_VER */
2198
2199/* Alternate implementations can be added here... */
2200
2201#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002202
2203
2204/* Wrappers around sigaction() or signal(). */
2205
2206PyOS_sighandler_t
2207PyOS_getsig(int sig)
2208{
2209#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002210 struct sigaction context;
2211 if (sigaction(sig, NULL, &context) == -1)
2212 return SIG_ERR;
2213 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002214#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002215 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002216/* Special signal handling for the secure CRT in Visual Studio 2005 */
2217#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002218 switch (sig) {
2219 /* Only these signals are valid */
2220 case SIGINT:
2221 case SIGILL:
2222 case SIGFPE:
2223 case SIGSEGV:
2224 case SIGTERM:
2225 case SIGBREAK:
2226 case SIGABRT:
2227 break;
2228 /* Don't call signal() with other values or it will assert */
2229 default:
2230 return SIG_ERR;
2231 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002232#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002233 handler = signal(sig, SIG_IGN);
2234 if (handler != SIG_ERR)
2235 signal(sig, handler);
2236 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002237#endif
2238}
2239
2240PyOS_sighandler_t
2241PyOS_setsig(int sig, PyOS_sighandler_t handler)
2242{
2243#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002244 /* Some code in Modules/signalmodule.c depends on sigaction() being
2245 * used here if HAVE_SIGACTION is defined. Fix that if this code
2246 * changes to invalidate that assumption.
2247 */
2248 struct sigaction context, ocontext;
2249 context.sa_handler = handler;
2250 sigemptyset(&context.sa_mask);
2251 context.sa_flags = 0;
2252 if (sigaction(sig, &context, &ocontext) == -1)
2253 return SIG_ERR;
2254 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002255#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002256 PyOS_sighandler_t oldhandler;
2257 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002258#ifdef HAVE_SIGINTERRUPT
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002259 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002260#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002261 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002262#endif
2263}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264
2265/* Deprecated C API functions still provided for binary compatiblity */
2266
2267#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002268PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002269PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2270{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002271 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272}
2273
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002274#undef PyParser_SimpleParseString
2275PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002276PyParser_SimpleParseString(const char *str, int start)
2277{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002278 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002280
2281#undef PyRun_AnyFile
2282PyAPI_FUNC(int)
2283PyRun_AnyFile(FILE *fp, const char *name)
2284{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002285 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002286}
2287
2288#undef PyRun_AnyFileEx
2289PyAPI_FUNC(int)
2290PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2291{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002292 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002293}
2294
2295#undef PyRun_AnyFileFlags
2296PyAPI_FUNC(int)
2297PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2298{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002299 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002300}
2301
2302#undef PyRun_File
2303PyAPI_FUNC(PyObject *)
2304PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2305{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002306 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002307}
2308
2309#undef PyRun_FileEx
2310PyAPI_FUNC(PyObject *)
2311PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2312{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002313 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002314}
2315
2316#undef PyRun_FileFlags
2317PyAPI_FUNC(PyObject *)
2318PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002319 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002320{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002321 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002322}
2323
2324#undef PyRun_SimpleFile
2325PyAPI_FUNC(int)
2326PyRun_SimpleFile(FILE *f, const char *p)
2327{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002328 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002329}
2330
2331#undef PyRun_SimpleFileEx
2332PyAPI_FUNC(int)
2333PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2334{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002335 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002336}
2337
2338
2339#undef PyRun_String
2340PyAPI_FUNC(PyObject *)
2341PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2342{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002343 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002344}
2345
2346#undef PyRun_SimpleString
2347PyAPI_FUNC(int)
2348PyRun_SimpleString(const char *s)
2349{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002350 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002351}
2352
2353#undef Py_CompileString
2354PyAPI_FUNC(PyObject *)
2355Py_CompileString(const char *str, const char *p, int s)
2356{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002357 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002358}
2359
2360#undef PyRun_InteractiveOne
2361PyAPI_FUNC(int)
2362PyRun_InteractiveOne(FILE *f, const char *p)
2363{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002364 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002365}
2366
2367#undef PyRun_InteractiveLoop
2368PyAPI_FUNC(int)
2369PyRun_InteractiveLoop(FILE *f, const char *p)
2370{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002371 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002372}
2373
2374#ifdef __cplusplus
2375}
2376#endif