blob: 84d72f071401bf0efdb54c241e36a47df37bd3ba [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
Victor Stinner148051a2010-05-20 21:00:34 +0000267 /* Initialize _warnings. */
268 _PyWarnings_Init();
269
Martin v. Löwis011e8422009-05-05 04:43:17 +0000270#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000271 /* On Unix, set the file system encoding according to the
272 user's preference, if the CODESET names a well-known
273 Python codec, and Py_FileSystemDefaultEncoding isn't
274 initialized by other means. Also set the encoding of
275 stdin and stdout if these are terminals. */
Martin v. Löwis011e8422009-05-05 04:43:17 +0000276
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000277 codeset = get_codeset();
278 if (codeset) {
279 if (!Py_FileSystemDefaultEncoding)
280 Py_FileSystemDefaultEncoding = codeset;
281 else
282 free(codeset);
283 }
Martin v. Löwis011e8422009-05-05 04:43:17 +0000284#endif
285
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000286 if (install_sigs)
287 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000288
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000289 /* Initialize warnings. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000290 if (PySys_HasWarnOptions()) {
291 PyObject *warnings_module = PyImport_ImportModule("warnings");
292 if (!warnings_module)
293 PyErr_Clear();
294 Py_XDECREF(warnings_module);
295 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000296
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000297 initmain(); /* Module __main__ */
298 if (initstdio() < 0)
299 Py_FatalError(
300 "Py_Initialize: can't initialize sys standard streams");
301
302 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000303#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000304 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000305#endif /* WITH_THREAD */
Victor Stinnerffbc2f62010-03-21 21:48:45 +0000306
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000307 if (!Py_NoSiteFlag)
308 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000309}
310
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000311void
312Py_Initialize(void)
313{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000314 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000315}
316
317
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000318#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000319extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000320#endif
321
Guido van Rossume8432ac2007-07-09 15:04:50 +0000322/* Flush stdout and stderr */
323
Neal Norwitz2bad9702007-08-27 06:19:22 +0000324static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000325flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000326{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000327 PyObject *fout = PySys_GetObject("stdout");
328 PyObject *ferr = PySys_GetObject("stderr");
329 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000330
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000331 if (fout != NULL && fout != Py_None) {
332 tmp = PyObject_CallMethod(fout, "flush", "");
333 if (tmp == NULL)
Antoine Pitroub61d5c92010-08-08 20:49:19 +0000334 PyErr_WriteUnraisable(fout);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000335 else
336 Py_DECREF(tmp);
337 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000338
Victor Stinnerebb5a882010-05-14 01:03:14 +0000339 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000340 tmp = PyObject_CallMethod(ferr, "flush", "");
341 if (tmp == NULL)
342 PyErr_Clear();
343 else
344 Py_DECREF(tmp);
345 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000346}
347
Guido van Rossum25ce5661997-08-02 03:10:38 +0000348/* Undo the effect of Py_Initialize().
349
350 Beware: if multiple interpreter and/or thread states exist, these
351 are not wiped out; only the current thread and interpreter state
352 are deleted. But since everything else is deleted, those other
353 interpreter and thread states should no longer be used.
354
355 (XXX We should do better, e.g. wipe out all interpreters and
356 threads.)
357
358 Locking: as above.
359
360*/
361
362void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000363Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000364{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000365 PyInterpreterState *interp;
366 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000367
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000368 if (!initialized)
369 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000370
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000371 wait_for_thread_shutdown();
Antoine Pitroucefb3162009-10-20 22:08:36 +0000372
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000373 /* The interpreter is still entirely intact at this point, and the
374 * exit funcs may be relying on that. In particular, if some thread
375 * or exit func is still waiting to do an import, the import machinery
376 * expects Py_IsInitialized() to return true. So don't say the
377 * interpreter is uninitialized until after the exit funcs have run.
378 * Note that Threading.py uses an exit func to do a join on all the
379 * threads created thru it, so this also protects pending imports in
380 * the threads created via Threading.
381 */
382 call_py_exitfuncs();
383 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000384
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000385 /* Flush stdout+stderr */
386 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000387
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000388 /* Get current thread state and interpreter pointer */
389 tstate = PyThreadState_GET();
390 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000391
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000392 /* Disable signal handling */
393 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000394
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000395 /* Clear type lookup cache */
396 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000397
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000398 /* Collect garbage. This may call finalizers; it's nice to call these
399 * before all modules are destroyed.
400 * XXX If a __del__ or weakref callback is triggered here, and tries to
401 * XXX import a module, bad things can happen, because Python no
402 * XXX longer believes it's initialized.
403 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
404 * XXX is easy to provoke that way. I've also seen, e.g.,
405 * XXX Exception exceptions.ImportError: 'No module named sha'
406 * XXX in <function callback at 0x008F5718> ignored
407 * XXX but I'm unclear on exactly how that one happens. In any case,
408 * XXX I haven't seen a real-life report of either of these.
409 */
410 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000411#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000412 /* With COUNT_ALLOCS, it helps to run GC multiple times:
413 each collection might release some types from the type
414 list, so they become garbage. */
415 while (PyGC_Collect() > 0)
416 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000418
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000419 /* Destroy all modules */
420 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000421
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000422 /* Flush stdout+stderr (again, in case more was printed) */
423 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000424
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000425 /* Collect final garbage. This disposes of cycles created by
426 * new-style class definitions, for example.
427 * XXX This is disabled because it caused too many problems. If
428 * XXX a __del__ or weakref callback triggers here, Python code has
429 * XXX a hard time running, because even the sys module has been
430 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
431 * XXX One symptom is a sequence of information-free messages
432 * XXX coming from threads (if a __del__ or callback is invoked,
433 * XXX other threads can execute too, and any exception they encounter
434 * XXX triggers a comedy of errors as subsystem after subsystem
435 * XXX fails to find what it *expects* to find in sys to help report
436 * XXX the exception and consequent unexpected failures). I've also
437 * XXX seen segfaults then, after adding print statements to the
438 * XXX Python code getting called.
439 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000440#if 0
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000441 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000442#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000443
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000444 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
445 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000446
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000447 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000448#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000449 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000450#endif
451
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000452 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000453
Tim Peters9cf25ce2003-04-17 15:21:01 +0000454#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000455 /* Display all objects still alive -- this can invoke arbitrary
456 * __repr__ overrides, so requires a mostly-intact interpreter.
457 * Alas, a lot of stuff may still be alive now that will be cleaned
458 * up later.
459 */
460 if (Py_GETENV("PYTHONDUMPREFS"))
461 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000462#endif /* Py_TRACE_REFS */
463
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000464 /* Clear interpreter state */
465 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000466
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000467 /* Now we decref the exception classes. After this point nothing
468 can raise an exception. That's okay, because each Fini() method
469 below has been checked to make sure no exceptions are ever
470 raised.
471 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000472
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000473 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000474
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000475 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000476#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000477 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000478#endif /* WITH_THREAD */
479
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000480 /* Delete current thread */
481 PyThreadState_Swap(NULL);
482 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000483
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000484 /* Sundry finalizers */
485 PyMethod_Fini();
486 PyFrame_Fini();
487 PyCFunction_Fini();
488 PyTuple_Fini();
489 PyList_Fini();
490 PySet_Fini();
491 PyBytes_Fini();
492 PyByteArray_Fini();
493 PyLong_Fini();
494 PyFloat_Fini();
495 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000496
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000497 /* Cleanup Unicode implementation */
498 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000499
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000500 /* reset file system default encoding */
501 if (!Py_HasFileSystemDefaultEncoding) {
502 free((char*)Py_FileSystemDefaultEncoding);
503 Py_FileSystemDefaultEncoding = NULL;
504 }
Christian Heimesc8967002007-11-30 10:18:26 +0000505
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000506 /* XXX Still allocated:
507 - various static ad-hoc pointers to interned strings
508 - int and float free list blocks
509 - whatever various modules and libraries allocate
510 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000511
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000512 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000513
Tim Peters269b2a62003-04-17 19:52:29 +0000514#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000515 /* Display addresses (& refcnts) of all objects still alive.
516 * An address can be used to find the repr of the object, printed
517 * above by _Py_PrintReferences.
518 */
519 if (Py_GETENV("PYTHONDUMPREFS"))
520 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000521#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000522#ifdef PYMALLOC_DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000523 if (Py_GETENV("PYTHONMALLOCSTATS"))
524 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000525#endif
526
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000527 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000528}
529
530/* Create and initialize a new interpreter and thread, and return the
531 new thread. This requires that Py_Initialize() has been called
532 first.
533
534 Unsuccessful initialization yields a NULL pointer. Note that *no*
535 exception information is available even in this case -- the
536 exception information is held in the thread, and there is no
537 thread.
538
539 Locking: as above.
540
541*/
542
543PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000544Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000545{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000546 PyInterpreterState *interp;
547 PyThreadState *tstate, *save_tstate;
548 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000549
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000550 if (!initialized)
551 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000552
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000553 interp = PyInterpreterState_New();
554 if (interp == NULL)
555 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000557 tstate = PyThreadState_New(interp);
558 if (tstate == NULL) {
559 PyInterpreterState_Delete(interp);
560 return NULL;
561 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000563 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000565 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000567 interp->modules = PyDict_New();
568 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000570 bimod = _PyImport_FindExtension("builtins", "builtins");
571 if (bimod != NULL) {
572 interp->builtins = PyModule_GetDict(bimod);
573 if (interp->builtins == NULL)
574 goto handle_error;
575 Py_INCREF(interp->builtins);
576 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000577
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000578 /* initialize builtin exceptions */
579 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000580
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000581 sysmod = _PyImport_FindExtension("sys", "sys");
582 if (bimod != NULL && sysmod != NULL) {
583 PyObject *pstderr;
584 interp->sysdict = PyModule_GetDict(sysmod);
585 if (interp->sysdict == NULL)
586 goto handle_error;
587 Py_INCREF(interp->sysdict);
588 PySys_SetPath(Py_GetPath());
589 PyDict_SetItemString(interp->sysdict, "modules",
590 interp->modules);
591 /* Set up a preliminary stderr printer until we have enough
592 infrastructure for the io module in place. */
593 pstderr = PyFile_NewStdPrinter(fileno(stderr));
594 if (pstderr == NULL)
595 Py_FatalError("Py_Initialize: can't set preliminary stderr");
596 PySys_SetObject("stderr", pstderr);
597 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000598
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000599 _PyImportHooks_Init();
600 if (initstdio() < 0)
601 Py_FatalError(
602 "Py_Initialize: can't initialize sys standard streams");
603 initmain();
604 if (!Py_NoSiteFlag)
605 initsite();
606 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000607
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000608 if (!PyErr_Occurred())
609 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610
Thomas Wouters89f507f2006-12-13 04:49:30 +0000611handle_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000612 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000613
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000614 PyErr_Print();
615 PyThreadState_Clear(tstate);
616 PyThreadState_Swap(save_tstate);
617 PyThreadState_Delete(tstate);
618 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000619
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000620 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621}
622
623/* Delete an interpreter and its last thread. This requires that the
624 given thread state is current, that the thread has no remaining
625 frames, and that it is its interpreter's only remaining thread.
626 It is a fatal error to violate these constraints.
627
628 (Py_Finalize() doesn't have these constraints -- it zaps
629 everything, regardless.)
630
631 Locking: as above.
632
633*/
634
635void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000636Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000638 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000639
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000640 if (tstate != PyThreadState_GET())
641 Py_FatalError("Py_EndInterpreter: thread is not current");
642 if (tstate->frame != NULL)
643 Py_FatalError("Py_EndInterpreter: thread still has a frame");
644 if (tstate != interp->tstate_head || tstate->next != NULL)
645 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000646
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000647 PyImport_Cleanup();
648 PyInterpreterState_Clear(interp);
649 PyThreadState_Swap(NULL);
650 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000651}
652
Martin v. Löwis790465f2008-04-05 20:41:37 +0000653static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000654
655void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000656Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000657{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000658 if (pn && *pn)
659 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000660}
661
Martin v. Löwis790465f2008-04-05 20:41:37 +0000662wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000663Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000664{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000665 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000666}
667
Martin v. Löwis790465f2008-04-05 20:41:37 +0000668static wchar_t *default_home = NULL;
669static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000670
671void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000672Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000673{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000674 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000675}
676
Martin v. Löwis790465f2008-04-05 20:41:37 +0000677wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000678Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000679{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000680 wchar_t *home = default_home;
681 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
682 char* chome = Py_GETENV("PYTHONHOME");
683 if (chome) {
684 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
685 if (r != (size_t)-1 && r <= PATH_MAX)
686 home = env_home;
687 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000688
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000689 }
690 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000691}
692
Guido van Rossum6135a871995-01-09 17:53:26 +0000693/* Create __main__ module */
694
695static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000696initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000697{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000698 PyObject *m, *d;
699 m = PyImport_AddModule("__main__");
700 if (m == NULL)
701 Py_FatalError("can't create __main__ module");
702 d = PyModule_GetDict(m);
703 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
704 PyObject *bimod = PyImport_ImportModule("builtins");
705 if (bimod == NULL ||
706 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
707 Py_FatalError("can't add __builtins__ to __main__");
708 Py_DECREF(bimod);
709 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000710}
711
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000712/* Import the site module (not into __main__ though) */
713
714static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000715initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000716{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000717 PyObject *m, *f;
718 m = PyImport_ImportModule("site");
719 if (m == NULL) {
720 f = PySys_GetObject("stderr");
721 if (f == NULL || f == Py_None)
722 return;
723 if (Py_VerboseFlag) {
724 PyFile_WriteString(
725 "'import site' failed; traceback:\n", f);
726 PyErr_Print();
727 }
728 else {
729 PyFile_WriteString(
730 "'import site' failed; use -v for traceback\n", f);
731 PyErr_Clear();
732 }
733 }
734 else {
735 Py_DECREF(m);
736 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000737}
738
Antoine Pitrou05608432009-01-09 18:53:14 +0000739static PyObject*
740create_stdio(PyObject* io,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000741 int fd, int write_mode, char* name,
742 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000743{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000744 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
745 const char* mode;
746 PyObject *line_buffering;
747 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000748
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000749 /* stdin is always opened in buffered mode, first because it shouldn't
750 make a difference in common use cases, second because TextIOWrapper
751 depends on the presence of a read1() method which only exists on
752 buffered streams.
753 */
754 if (Py_UnbufferedStdioFlag && write_mode)
755 buffering = 0;
756 else
757 buffering = -1;
758 if (write_mode)
759 mode = "wb";
760 else
761 mode = "rb";
762 buf = PyObject_CallMethod(io, "open", "isiOOOi",
763 fd, mode, buffering,
764 Py_None, Py_None, Py_None, 0);
765 if (buf == NULL)
766 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000767
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000768 if (buffering) {
769 raw = PyObject_GetAttrString(buf, "raw");
770 if (raw == NULL)
771 goto error;
772 }
773 else {
774 raw = buf;
775 Py_INCREF(raw);
776 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000777
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000778 text = PyUnicode_FromString(name);
779 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
780 goto error;
781 res = PyObject_CallMethod(raw, "isatty", "");
782 if (res == NULL)
783 goto error;
784 isatty = PyObject_IsTrue(res);
785 Py_DECREF(res);
786 if (isatty == -1)
787 goto error;
788 if (isatty || Py_UnbufferedStdioFlag)
789 line_buffering = Py_True;
790 else
791 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000792
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000793 Py_CLEAR(raw);
794 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000795
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000796 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
797 buf, encoding, errors,
798 "\n", line_buffering);
799 Py_CLEAR(buf);
800 if (stream == NULL)
801 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000802
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000803 if (write_mode)
804 mode = "w";
805 else
806 mode = "r";
807 text = PyUnicode_FromString(mode);
808 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
809 goto error;
810 Py_CLEAR(text);
811 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000812
813error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000814 Py_XDECREF(buf);
815 Py_XDECREF(stream);
816 Py_XDECREF(text);
817 Py_XDECREF(raw);
818 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000819}
820
Georg Brandl1a3284e2007-12-02 09:40:06 +0000821/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000822static int
823initstdio(void)
824{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000825 PyObject *iomod = NULL, *wrapper;
826 PyObject *bimod = NULL;
827 PyObject *m;
828 PyObject *std = NULL;
829 int status = 0, fd;
830 PyObject * encoding_attr;
831 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000832
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000833 /* Hack to avoid a nasty recursion issue when Python is invoked
834 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
835 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
836 goto error;
837 }
838 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000839
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000840 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
841 goto error;
842 }
843 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000844
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000845 if (!(bimod = PyImport_ImportModule("builtins"))) {
846 goto error;
847 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000848
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000849 if (!(iomod = PyImport_ImportModule("io"))) {
850 goto error;
851 }
852 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
853 goto error;
854 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000855
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000856 /* Set builtins.open */
857 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
858 goto error;
859 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000860
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000861 encoding = Py_GETENV("PYTHONIOENCODING");
862 errors = NULL;
863 if (encoding) {
864 encoding = strdup(encoding);
865 errors = strchr(encoding, ':');
866 if (errors) {
867 *errors = '\0';
868 errors++;
869 }
870 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000871
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000872 /* Set sys.stdin */
873 fd = fileno(stdin);
874 /* Under some conditions stdin, stdout and stderr may not be connected
875 * and fileno() may point to an invalid file descriptor. For example
876 * GUI apps don't have valid standard streams by default.
877 */
878 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000879#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000880 std = Py_None;
881 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000882#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000883 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000884#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000885 }
886 else {
887 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
888 if (std == NULL)
889 goto error;
890 } /* if (fd < 0) */
891 PySys_SetObject("__stdin__", std);
892 PySys_SetObject("stdin", std);
893 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000894
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000895 /* Set sys.stdout */
896 fd = fileno(stdout);
897 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000898#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000899 std = Py_None;
900 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000901#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000902 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000903#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000904 }
905 else {
906 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
907 if (std == NULL)
908 goto error;
909 } /* if (fd < 0) */
910 PySys_SetObject("__stdout__", std);
911 PySys_SetObject("stdout", std);
912 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000913
Guido van Rossum98297ee2007-11-06 21:34:58 +0000914#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000915 /* Set sys.stderr, replaces the preliminary stderr */
916 fd = fileno(stderr);
917 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000918#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000919 std = Py_None;
920 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000921#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000922 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000923#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000924 }
925 else {
926 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
927 if (std == NULL)
928 goto error;
929 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000930
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000931 /* Same as hack above, pre-import stderr's codec to avoid recursion
932 when import.c tries to write to stderr in verbose mode. */
933 encoding_attr = PyObject_GetAttrString(std, "encoding");
934 if (encoding_attr != NULL) {
935 const char * encoding;
936 encoding = _PyUnicode_AsString(encoding_attr);
937 if (encoding != NULL) {
938 _PyCodec_Lookup(encoding);
939 }
940 }
941 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000942
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000943 PySys_SetObject("__stderr__", std);
944 PySys_SetObject("stderr", std);
945 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000946#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000947
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000948 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000949 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000950 status = -1;
951 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000952
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000953 if (encoding)
954 free(encoding);
955 Py_XDECREF(bimod);
956 Py_XDECREF(iomod);
957 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000958}
959
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000960/* Parse input from a file and execute it */
961
962int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000963PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000964 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000965{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000966 if (filename == NULL)
967 filename = "???";
968 if (Py_FdIsInteractive(fp, filename)) {
969 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
970 if (closeit)
971 fclose(fp);
972 return err;
973 }
974 else
975 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000976}
977
978int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000979PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000980{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000981 PyObject *v;
982 int ret;
983 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000984
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000985 if (flags == NULL) {
986 flags = &local_flags;
987 local_flags.cf_flags = 0;
988 }
989 v = PySys_GetObject("ps1");
990 if (v == NULL) {
991 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
992 Py_XDECREF(v);
993 }
994 v = PySys_GetObject("ps2");
995 if (v == NULL) {
996 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
997 Py_XDECREF(v);
998 }
999 for (;;) {
1000 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1001 PRINT_TOTAL_REFS();
1002 if (ret == E_EOF)
1003 return 0;
1004 /*
1005 if (ret == E_NOMEM)
1006 return -1;
1007 */
1008 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001009}
1010
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001011/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001012static int PARSER_FLAGS(PyCompilerFlags *flags)
1013{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001014 int parser_flags = 0;
1015 if (!flags)
1016 return 0;
1017 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1018 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1019 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1020 parser_flags |= PyPARSE_IGNORE_COOKIE;
1021 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1022 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1023 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001024}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001025
Thomas Wouters89f507f2006-12-13 04:49:30 +00001026#if 0
1027/* Keep an example of flags with future keyword support. */
1028#define PARSER_FLAGS(flags) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001029 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1030 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1031 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1032 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001033#endif
1034
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001035int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001036PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001037{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001038 PyObject *m, *d, *v, *w, *oenc = NULL;
1039 mod_ty mod;
1040 PyArena *arena;
1041 char *ps1 = "", *ps2 = "", *enc = NULL;
1042 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001043
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001044 if (fp == stdin) {
1045 /* Fetch encoding from sys.stdin */
1046 v = PySys_GetObject("stdin");
1047 if (v == NULL || v == Py_None)
1048 return -1;
1049 oenc = PyObject_GetAttrString(v, "encoding");
1050 if (!oenc)
1051 return -1;
1052 enc = _PyUnicode_AsString(oenc);
1053 }
1054 v = PySys_GetObject("ps1");
1055 if (v != NULL) {
1056 v = PyObject_Str(v);
1057 if (v == NULL)
1058 PyErr_Clear();
1059 else if (PyUnicode_Check(v))
1060 ps1 = _PyUnicode_AsString(v);
1061 }
1062 w = PySys_GetObject("ps2");
1063 if (w != NULL) {
1064 w = PyObject_Str(w);
1065 if (w == NULL)
1066 PyErr_Clear();
1067 else if (PyUnicode_Check(w))
1068 ps2 = _PyUnicode_AsString(w);
1069 }
1070 arena = PyArena_New();
1071 if (arena == NULL) {
1072 Py_XDECREF(v);
1073 Py_XDECREF(w);
1074 Py_XDECREF(oenc);
1075 return -1;
1076 }
1077 mod = PyParser_ASTFromFile(fp, filename, enc,
1078 Py_single_input, ps1, ps2,
1079 flags, &errcode, arena);
1080 Py_XDECREF(v);
1081 Py_XDECREF(w);
1082 Py_XDECREF(oenc);
1083 if (mod == NULL) {
1084 PyArena_Free(arena);
1085 if (errcode == E_EOF) {
1086 PyErr_Clear();
1087 return E_EOF;
1088 }
1089 PyErr_Print();
1090 return -1;
1091 }
1092 m = PyImport_AddModule("__main__");
1093 if (m == NULL) {
1094 PyArena_Free(arena);
1095 return -1;
1096 }
1097 d = PyModule_GetDict(m);
1098 v = run_mod(mod, filename, d, d, flags, arena);
1099 PyArena_Free(arena);
1100 flush_io();
1101 if (v == NULL) {
1102 PyErr_Print();
1103 return -1;
1104 }
1105 Py_DECREF(v);
1106 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001107}
1108
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001109/* Check whether a file maybe a pyc file: Look at the extension,
1110 the file type, and, if we may close it, at the first few bytes. */
1111
1112static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001113maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001114{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001115 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1116 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001117
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001118 /* Only look into the file if we are allowed to close it, since
1119 it then should also be seekable. */
1120 if (closeit) {
1121 /* Read only two bytes of the magic. If the file was opened in
1122 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1123 be read as they are on disk. */
1124 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1125 unsigned char buf[2];
1126 /* Mess: In case of -x, the stream is NOT at its start now,
1127 and ungetc() was used to push back the first newline,
1128 which makes the current stream position formally undefined,
1129 and a x-platform nightmare.
1130 Unfortunately, we have no direct way to know whether -x
1131 was specified. So we use a terrible hack: if the current
1132 stream position is not 0, we assume -x was specified, and
1133 give up. Bug 132850 on SourceForge spells out the
1134 hopelessness of trying anything else (fseek and ftell
1135 don't work predictably x-platform for text-mode files).
1136 */
1137 int ispyc = 0;
1138 if (ftell(fp) == 0) {
1139 if (fread(buf, 1, 2, fp) == 2 &&
1140 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1141 ispyc = 1;
1142 rewind(fp);
1143 }
1144 return ispyc;
1145 }
1146 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001147}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001148
Guido van Rossum0df002c2000-08-27 19:21:52 +00001149int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001150PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001151 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001152{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001153 PyObject *m, *d, *v;
1154 const char *ext;
1155 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001156
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001157 m = PyImport_AddModule("__main__");
1158 if (m == NULL)
1159 return -1;
1160 d = PyModule_GetDict(m);
1161 if (PyDict_GetItemString(d, "__file__") == NULL) {
1162 PyObject *f;
Victor Stinner25bb0fd2010-06-17 23:23:37 +00001163 f = PyUnicode_FromString(filename);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001164 if (f == NULL)
1165 return -1;
1166 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1167 Py_DECREF(f);
1168 return -1;
1169 }
1170 set_file_name = 1;
1171 Py_DECREF(f);
1172 }
1173 len = strlen(filename);
1174 ext = filename + len - (len > 4 ? 4 : 0);
1175 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1176 /* Try to run a pyc file. First, re-open in binary */
1177 if (closeit)
1178 fclose(fp);
1179 if ((fp = fopen(filename, "rb")) == NULL) {
1180 fprintf(stderr, "python: Can't reopen .pyc file\n");
1181 ret = -1;
1182 goto done;
1183 }
1184 /* Turn on optimization if a .pyo file is given */
1185 if (strcmp(ext, ".pyo") == 0)
1186 Py_OptimizeFlag = 1;
1187 v = run_pyc_file(fp, filename, d, d, flags);
1188 } else {
1189 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1190 closeit, flags);
1191 }
1192 flush_io();
1193 if (v == NULL) {
1194 PyErr_Print();
1195 ret = -1;
1196 goto done;
1197 }
1198 Py_DECREF(v);
1199 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001200 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001201 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1202 PyErr_Clear();
1203 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001204}
1205
1206int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001207PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001208{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001209 PyObject *m, *d, *v;
1210 m = PyImport_AddModule("__main__");
1211 if (m == NULL)
1212 return -1;
1213 d = PyModule_GetDict(m);
1214 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1215 if (v == NULL) {
1216 PyErr_Print();
1217 return -1;
1218 }
1219 Py_DECREF(v);
1220 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001221}
1222
Barry Warsaw035574d1997-08-29 22:07:17 +00001223static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001224parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001225 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001226{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001227 long hold;
1228 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001229
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001230 /* old style errors */
1231 if (PyTuple_Check(err))
1232 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1233 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001234
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001235 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001236
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001237 if (! (v = PyObject_GetAttrString(err, "msg")))
1238 goto finally;
1239 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001240
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001241 if (!(v = PyObject_GetAttrString(err, "filename")))
1242 goto finally;
1243 if (v == Py_None)
1244 *filename = NULL;
1245 else if (! (*filename = _PyUnicode_AsString(v)))
1246 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001247
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001248 Py_DECREF(v);
1249 if (!(v = PyObject_GetAttrString(err, "lineno")))
1250 goto finally;
1251 hold = PyLong_AsLong(v);
1252 Py_DECREF(v);
1253 v = NULL;
1254 if (hold < 0 && PyErr_Occurred())
1255 goto finally;
1256 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001257
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001258 if (!(v = PyObject_GetAttrString(err, "offset")))
1259 goto finally;
1260 if (v == Py_None) {
1261 *offset = -1;
1262 Py_DECREF(v);
1263 v = NULL;
1264 } else {
1265 hold = PyLong_AsLong(v);
1266 Py_DECREF(v);
1267 v = NULL;
1268 if (hold < 0 && PyErr_Occurred())
1269 goto finally;
1270 *offset = (int)hold;
1271 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001272
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001273 if (!(v = PyObject_GetAttrString(err, "text")))
1274 goto finally;
1275 if (v == Py_None)
1276 *text = NULL;
1277 else if (!PyUnicode_Check(v) ||
1278 !(*text = _PyUnicode_AsString(v)))
1279 goto finally;
1280 Py_DECREF(v);
1281 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001282
1283finally:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001284 Py_XDECREF(v);
1285 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001286}
1287
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001288void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001289PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001290{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001291 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001292}
1293
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001294static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001295print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001296{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001297 char *nl;
1298 if (offset >= 0) {
1299 if (offset > 0 && offset == (int)strlen(text))
1300 offset--;
1301 for (;;) {
1302 nl = strchr(text, '\n');
1303 if (nl == NULL || nl-text >= offset)
1304 break;
1305 offset -= (int)(nl+1-text);
1306 text = nl+1;
1307 }
1308 while (*text == ' ' || *text == '\t') {
1309 text++;
1310 offset--;
1311 }
1312 }
1313 PyFile_WriteString(" ", f);
1314 PyFile_WriteString(text, f);
1315 if (*text == '\0' || text[strlen(text)-1] != '\n')
1316 PyFile_WriteString("\n", f);
1317 if (offset == -1)
1318 return;
1319 PyFile_WriteString(" ", f);
1320 offset--;
1321 while (offset > 0) {
1322 PyFile_WriteString(" ", f);
1323 offset--;
1324 }
1325 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001326}
1327
Guido van Rossum66e8e862001-03-23 17:54:43 +00001328static void
1329handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001330{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001331 PyObject *exception, *value, *tb;
1332 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001333
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001334 if (Py_InspectFlag)
1335 /* Don't exit if -i flag was given. This flag is set to 0
1336 * when entering interactive mode for inspecting. */
1337 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001338
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001339 PyErr_Fetch(&exception, &value, &tb);
1340 fflush(stdout);
1341 if (value == NULL || value == Py_None)
1342 goto done;
1343 if (PyExceptionInstance_Check(value)) {
1344 /* The error code should be in the `code' attribute. */
1345 PyObject *code = PyObject_GetAttrString(value, "code");
1346 if (code) {
1347 Py_DECREF(value);
1348 value = code;
1349 if (value == Py_None)
1350 goto done;
1351 }
1352 /* If we failed to dig out the 'code' attribute,
1353 just let the else clause below print the error. */
1354 }
1355 if (PyLong_Check(value))
1356 exitcode = (int)PyLong_AsLong(value);
1357 else {
Victor Stinner2e71d012010-05-17 09:35:44 +00001358 PyObject *sys_stderr = PySys_GetObject("stderr");
1359 if (sys_stderr != NULL)
1360 PyObject_CallMethod(sys_stderr, "flush", NULL);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001361 PyObject_Print(value, stderr, Py_PRINT_RAW);
Victor Stinner2e71d012010-05-17 09:35:44 +00001362 fflush(stderr);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001363 PySys_WriteStderr("\n");
1364 exitcode = 1;
1365 }
Tim Peterscf615b52003-04-19 18:47:02 +00001366 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001367 /* Restore and clear the exception info, in order to properly decref
1368 * the exception, value, and traceback. If we just exit instead,
1369 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1370 * some finalizers from running.
1371 */
1372 PyErr_Restore(exception, value, tb);
1373 PyErr_Clear();
1374 Py_Exit(exitcode);
1375 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001376}
1377
1378void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001379PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001380{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001381 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001382
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001383 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1384 handle_system_exit();
1385 }
1386 PyErr_Fetch(&exception, &v, &tb);
1387 if (exception == NULL)
1388 return;
1389 PyErr_NormalizeException(&exception, &v, &tb);
1390 if (tb == NULL) {
1391 tb = Py_None;
1392 Py_INCREF(tb);
1393 }
1394 PyException_SetTraceback(v, tb);
1395 if (exception == NULL)
1396 return;
1397 /* Now we know v != NULL too */
1398 if (set_sys_last_vars) {
1399 PySys_SetObject("last_type", exception);
1400 PySys_SetObject("last_value", v);
1401 PySys_SetObject("last_traceback", tb);
1402 }
1403 hook = PySys_GetObject("excepthook");
1404 if (hook) {
1405 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1406 PyObject *result = PyEval_CallObject(hook, args);
1407 if (result == NULL) {
1408 PyObject *exception2, *v2, *tb2;
1409 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1410 handle_system_exit();
1411 }
1412 PyErr_Fetch(&exception2, &v2, &tb2);
1413 PyErr_NormalizeException(&exception2, &v2, &tb2);
1414 /* It should not be possible for exception2 or v2
1415 to be NULL. However PyErr_Display() can't
1416 tolerate NULLs, so just be safe. */
1417 if (exception2 == NULL) {
1418 exception2 = Py_None;
1419 Py_INCREF(exception2);
1420 }
1421 if (v2 == NULL) {
1422 v2 = Py_None;
1423 Py_INCREF(v2);
1424 }
1425 fflush(stdout);
1426 PySys_WriteStderr("Error in sys.excepthook:\n");
1427 PyErr_Display(exception2, v2, tb2);
1428 PySys_WriteStderr("\nOriginal exception was:\n");
1429 PyErr_Display(exception, v, tb);
1430 Py_DECREF(exception2);
1431 Py_DECREF(v2);
1432 Py_XDECREF(tb2);
1433 }
1434 Py_XDECREF(result);
1435 Py_XDECREF(args);
1436 } else {
1437 PySys_WriteStderr("sys.excepthook is missing\n");
1438 PyErr_Display(exception, v, tb);
1439 }
1440 Py_XDECREF(exception);
1441 Py_XDECREF(v);
1442 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001443}
1444
Benjamin Petersone6528212008-07-15 15:32:09 +00001445static void
1446print_exception(PyObject *f, PyObject *value)
1447{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001448 int err = 0;
1449 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001450
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001451 if (!PyExceptionInstance_Check(value)) {
1452 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1453 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1454 PyFile_WriteString(" found\n", f);
1455 return;
1456 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001457
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001458 Py_INCREF(value);
1459 fflush(stdout);
1460 type = (PyObject *) Py_TYPE(value);
1461 tb = PyException_GetTraceback(value);
1462 if (tb && tb != Py_None)
1463 err = PyTraceBack_Print(tb, f);
1464 if (err == 0 &&
1465 PyObject_HasAttrString(value, "print_file_and_line"))
1466 {
1467 PyObject *message;
1468 const char *filename, *text;
1469 int lineno, offset;
1470 if (!parse_syntax_error(value, &message, &filename,
1471 &lineno, &offset, &text))
1472 PyErr_Clear();
1473 else {
1474 char buf[10];
1475 PyFile_WriteString(" File \"", f);
1476 if (filename == NULL)
1477 PyFile_WriteString("<string>", f);
1478 else
1479 PyFile_WriteString(filename, f);
1480 PyFile_WriteString("\", line ", f);
1481 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1482 PyFile_WriteString(buf, f);
1483 PyFile_WriteString("\n", f);
1484 if (text != NULL)
1485 print_error_text(f, offset, text);
1486 Py_DECREF(value);
1487 value = message;
1488 /* Can't be bothered to check all those
1489 PyFile_WriteString() calls */
1490 if (PyErr_Occurred())
1491 err = -1;
1492 }
1493 }
1494 if (err) {
1495 /* Don't do anything else */
1496 }
1497 else {
1498 PyObject* moduleName;
1499 char* className;
1500 assert(PyExceptionClass_Check(type));
1501 className = PyExceptionClass_Name(type);
1502 if (className != NULL) {
1503 char *dot = strrchr(className, '.');
1504 if (dot != NULL)
1505 className = dot+1;
1506 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001507
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001508 moduleName = PyObject_GetAttrString(type, "__module__");
1509 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1510 {
1511 Py_DECREF(moduleName);
1512 err = PyFile_WriteString("<unknown>", f);
1513 }
1514 else {
1515 char* modstr = _PyUnicode_AsString(moduleName);
1516 if (modstr && strcmp(modstr, "builtins"))
1517 {
1518 err = PyFile_WriteString(modstr, f);
1519 err += PyFile_WriteString(".", f);
1520 }
1521 Py_DECREF(moduleName);
1522 }
1523 if (err == 0) {
1524 if (className == NULL)
1525 err = PyFile_WriteString("<unknown>", f);
1526 else
1527 err = PyFile_WriteString(className, f);
1528 }
1529 }
1530 if (err == 0 && (value != Py_None)) {
1531 PyObject *s = PyObject_Str(value);
1532 /* only print colon if the str() of the
1533 object is not the empty string
1534 */
1535 if (s == NULL)
1536 err = -1;
1537 else if (!PyUnicode_Check(s) ||
1538 PyUnicode_GetSize(s) != 0)
1539 err = PyFile_WriteString(": ", f);
1540 if (err == 0)
1541 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1542 Py_XDECREF(s);
1543 }
1544 /* try to write a newline in any case */
1545 err += PyFile_WriteString("\n", f);
1546 Py_XDECREF(tb);
1547 Py_DECREF(value);
1548 /* If an error happened here, don't show it.
1549 XXX This is wrong, but too many callers rely on this behavior. */
1550 if (err != 0)
1551 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001552}
1553
1554static const char *cause_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001555 "\nThe above exception was the direct cause "
1556 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001557
1558static const char *context_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001559 "\nDuring handling of the above exception, "
1560 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001561
1562static void
1563print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1564{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001565 int err = 0, res;
1566 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001567
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001568 if (seen != NULL) {
1569 /* Exception chaining */
1570 if (PySet_Add(seen, value) == -1)
1571 PyErr_Clear();
1572 else if (PyExceptionInstance_Check(value)) {
1573 cause = PyException_GetCause(value);
1574 context = PyException_GetContext(value);
1575 if (cause) {
1576 res = PySet_Contains(seen, cause);
1577 if (res == -1)
1578 PyErr_Clear();
1579 if (res == 0) {
1580 print_exception_recursive(
1581 f, cause, seen);
1582 err |= PyFile_WriteString(
1583 cause_message, f);
1584 }
1585 }
1586 else if (context) {
1587 res = PySet_Contains(seen, context);
1588 if (res == -1)
1589 PyErr_Clear();
1590 if (res == 0) {
1591 print_exception_recursive(
1592 f, context, seen);
1593 err |= PyFile_WriteString(
1594 context_message, f);
1595 }
1596 }
1597 Py_XDECREF(context);
1598 Py_XDECREF(cause);
1599 }
1600 }
1601 print_exception(f, value);
1602 if (err != 0)
1603 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001604}
1605
Thomas Wouters477c8d52006-05-27 19:21:47 +00001606void
1607PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001608{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001609 PyObject *seen;
1610 PyObject *f = PySys_GetObject("stderr");
1611 if (f == Py_None) {
1612 /* pass */
1613 }
1614 else if (f == NULL) {
1615 _PyObject_Dump(value);
1616 fprintf(stderr, "lost sys.stderr\n");
1617 }
1618 else {
1619 /* We choose to ignore seen being possibly NULL, and report
1620 at least the main exception (it could be a MemoryError).
1621 */
1622 seen = PySet_New(NULL);
1623 if (seen == NULL)
1624 PyErr_Clear();
1625 print_exception_recursive(f, value, seen);
1626 Py_XDECREF(seen);
1627 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001628}
1629
Guido van Rossum82598051997-03-05 00:20:32 +00001630PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001631PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001632 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001633{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001634 PyObject *ret = NULL;
1635 mod_ty mod;
1636 PyArena *arena = PyArena_New();
1637 if (arena == NULL)
1638 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001639
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001640 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1641 if (mod != NULL)
1642 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1643 PyArena_Free(arena);
1644 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001645}
1646
1647PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001648PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001649 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001650{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001651 PyObject *ret;
1652 mod_ty mod;
1653 PyArena *arena = PyArena_New();
1654 if (arena == NULL)
1655 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001656
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001657 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1658 flags, NULL, arena);
1659 if (closeit)
1660 fclose(fp);
1661 if (mod == NULL) {
1662 PyArena_Free(arena);
1663 return NULL;
1664 }
1665 ret = run_mod(mod, filename, globals, locals, flags, arena);
1666 PyArena_Free(arena);
1667 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001668}
1669
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001670static void
1671flush_io(void)
1672{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001673 PyObject *f, *r;
1674 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001675
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001676 /* Save the current exception */
1677 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001678
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001679 f = PySys_GetObject("stderr");
1680 if (f != NULL) {
1681 r = PyObject_CallMethod(f, "flush", "");
1682 if (r)
1683 Py_DECREF(r);
1684 else
1685 PyErr_Clear();
1686 }
1687 f = PySys_GetObject("stdout");
1688 if (f != NULL) {
1689 r = PyObject_CallMethod(f, "flush", "");
1690 if (r)
1691 Py_DECREF(r);
1692 else
1693 PyErr_Clear();
1694 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001695
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001696 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001697}
1698
Guido van Rossum82598051997-03-05 00:20:32 +00001699static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001700run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001701 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001702{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001703 PyCodeObject *co;
1704 PyObject *v;
1705 co = PyAST_Compile(mod, filename, flags, arena);
1706 if (co == NULL)
1707 return NULL;
1708 v = PyEval_EvalCode(co, globals, locals);
1709 Py_DECREF(co);
1710 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001711}
1712
Guido van Rossum82598051997-03-05 00:20:32 +00001713static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001714run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001715 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001716{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001717 PyCodeObject *co;
1718 PyObject *v;
1719 long magic;
1720 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001721
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001722 magic = PyMarshal_ReadLongFromFile(fp);
1723 if (magic != PyImport_GetMagicNumber()) {
1724 PyErr_SetString(PyExc_RuntimeError,
1725 "Bad magic number in .pyc file");
1726 return NULL;
1727 }
1728 (void) PyMarshal_ReadLongFromFile(fp);
1729 v = PyMarshal_ReadLastObjectFromFile(fp);
1730 fclose(fp);
1731 if (v == NULL || !PyCode_Check(v)) {
1732 Py_XDECREF(v);
1733 PyErr_SetString(PyExc_RuntimeError,
1734 "Bad code object in .pyc file");
1735 return NULL;
1736 }
1737 co = (PyCodeObject *)v;
1738 v = PyEval_EvalCode(co, globals, locals);
1739 if (v && flags)
1740 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1741 Py_DECREF(co);
1742 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001743}
1744
Guido van Rossum82598051997-03-05 00:20:32 +00001745PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001746Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001747 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001748{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001749 PyCodeObject *co;
1750 mod_ty mod;
1751 PyArena *arena = PyArena_New();
1752 if (arena == NULL)
1753 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001754
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001755 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1756 if (mod == NULL) {
1757 PyArena_Free(arena);
1758 return NULL;
1759 }
1760 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1761 PyObject *result = PyAST_mod2obj(mod);
1762 PyArena_Free(arena);
1763 return result;
1764 }
1765 co = PyAST_Compile(mod, filename, flags, arena);
1766 PyArena_Free(arena);
1767 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001768}
1769
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001770struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001771Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001772{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001773 struct symtable *st;
1774 mod_ty mod;
1775 PyCompilerFlags flags;
1776 PyArena *arena = PyArena_New();
1777 if (arena == NULL)
1778 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001779
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001780 flags.cf_flags = 0;
1781 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1782 if (mod == NULL) {
1783 PyArena_Free(arena);
1784 return NULL;
1785 }
1786 st = PySymtable_Build(mod, filename, 0);
1787 PyArena_Free(arena);
1788 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001789}
1790
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791/* Preferred access to parser is through AST. */
1792mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001793PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001794 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001796 mod_ty mod;
1797 PyCompilerFlags localflags;
1798 perrdetail err;
1799 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001800
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001801 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1802 &_PyParser_Grammar, start, &err,
1803 &iflags);
1804 if (flags == NULL) {
1805 localflags.cf_flags = 0;
1806 flags = &localflags;
1807 }
1808 if (n) {
1809 flags->cf_flags |= iflags & PyCF_MASK;
1810 mod = PyAST_FromNode(n, flags, filename, arena);
1811 PyNode_Free(n);
1812 return mod;
1813 }
1814 else {
1815 err_input(&err);
1816 return NULL;
1817 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818}
1819
1820mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001821PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001822 int start, char *ps1,
1823 char *ps2, PyCompilerFlags *flags, int *errcode,
1824 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001826 mod_ty mod;
1827 PyCompilerFlags localflags;
1828 perrdetail err;
1829 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001830
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001831 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1832 &_PyParser_Grammar,
1833 start, ps1, ps2, &err, &iflags);
1834 if (flags == NULL) {
1835 localflags.cf_flags = 0;
1836 flags = &localflags;
1837 }
1838 if (n) {
1839 flags->cf_flags |= iflags & PyCF_MASK;
1840 mod = PyAST_FromNode(n, flags, filename, arena);
1841 PyNode_Free(n);
1842 return mod;
1843 }
1844 else {
1845 err_input(&err);
1846 if (errcode)
1847 *errcode = err.error;
1848 return NULL;
1849 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001850}
1851
Guido van Rossuma110aa61994-08-29 12:50:44 +00001852/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001853
Guido van Rossuma110aa61994-08-29 12:50:44 +00001854node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001855PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001856{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001857 perrdetail err;
1858 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1859 &_PyParser_Grammar,
1860 start, NULL, NULL, &err, flags);
1861 if (n == NULL)
1862 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001863
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001864 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001865}
1866
Guido van Rossuma110aa61994-08-29 12:50:44 +00001867/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001868
Guido van Rossuma110aa61994-08-29 12:50:44 +00001869node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001870PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001871{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001872 perrdetail err;
1873 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1874 start, &err, flags);
1875 if (n == NULL)
1876 err_input(&err);
1877 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001878}
1879
1880node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001881PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001882 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001883{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001884 perrdetail err;
1885 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1886 &_PyParser_Grammar, start, &err, flags);
1887 if (n == NULL)
1888 err_input(&err);
1889 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001890}
1891
1892node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001893PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001894{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001895 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001896}
1897
Guido van Rossum66ebd912003-04-17 16:02:26 +00001898/* May want to move a more generalized form of this to parsetok.c or
1899 even parser modules. */
1900
1901void
1902PyParser_SetError(perrdetail *err)
1903{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001904 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001905}
1906
Guido van Rossuma110aa61994-08-29 12:50:44 +00001907/* Set the error appropriate to the given input error code (see errcode.h) */
1908
1909static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001910err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001911{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001912 PyObject *v, *w, *errtype, *errtext;
1913 PyObject* u = NULL;
1914 char *msg = NULL;
1915 errtype = PyExc_SyntaxError;
1916 switch (err->error) {
1917 case E_ERROR:
1918 return;
1919 case E_SYNTAX:
1920 errtype = PyExc_IndentationError;
1921 if (err->expected == INDENT)
1922 msg = "expected an indented block";
1923 else if (err->token == INDENT)
1924 msg = "unexpected indent";
1925 else if (err->token == DEDENT)
1926 msg = "unexpected unindent";
1927 else {
1928 errtype = PyExc_SyntaxError;
1929 msg = "invalid syntax";
1930 }
1931 break;
1932 case E_TOKEN:
1933 msg = "invalid token";
1934 break;
1935 case E_EOFS:
1936 msg = "EOF while scanning triple-quoted string literal";
1937 break;
1938 case E_EOLS:
1939 msg = "EOL while scanning string literal";
1940 break;
1941 case E_INTR:
1942 if (!PyErr_Occurred())
1943 PyErr_SetNone(PyExc_KeyboardInterrupt);
1944 goto cleanup;
1945 case E_NOMEM:
1946 PyErr_NoMemory();
1947 goto cleanup;
1948 case E_EOF:
1949 msg = "unexpected EOF while parsing";
1950 break;
1951 case E_TABSPACE:
1952 errtype = PyExc_TabError;
1953 msg = "inconsistent use of tabs and spaces in indentation";
1954 break;
1955 case E_OVERFLOW:
1956 msg = "expression too long";
1957 break;
1958 case E_DEDENT:
1959 errtype = PyExc_IndentationError;
1960 msg = "unindent does not match any outer indentation level";
1961 break;
1962 case E_TOODEEP:
1963 errtype = PyExc_IndentationError;
1964 msg = "too many levels of indentation";
1965 break;
1966 case E_DECODE: {
1967 PyObject *type, *value, *tb;
1968 PyErr_Fetch(&type, &value, &tb);
1969 if (value != NULL) {
1970 u = PyObject_Str(value);
1971 if (u != NULL) {
1972 msg = _PyUnicode_AsString(u);
1973 }
1974 }
1975 if (msg == NULL)
1976 msg = "unknown decode error";
1977 Py_XDECREF(type);
1978 Py_XDECREF(value);
1979 Py_XDECREF(tb);
1980 break;
1981 }
1982 case E_LINECONT:
1983 msg = "unexpected character after line continuation character";
1984 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001985
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001986 case E_IDENTIFIER:
1987 msg = "invalid character in identifier";
1988 break;
1989 default:
1990 fprintf(stderr, "error=%d\n", err->error);
1991 msg = "unknown parsing error";
1992 break;
1993 }
1994 /* err->text may not be UTF-8 in case of decoding errors.
1995 Explicitly convert to an object. */
1996 if (!err->text) {
1997 errtext = Py_None;
1998 Py_INCREF(Py_None);
1999 } else {
2000 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2001 "replace");
2002 }
2003 v = Py_BuildValue("(ziiN)", err->filename,
2004 err->lineno, err->offset, errtext);
2005 w = NULL;
2006 if (v != NULL)
2007 w = Py_BuildValue("(sO)", msg, v);
2008 Py_XDECREF(u);
2009 Py_XDECREF(v);
2010 PyErr_SetObject(errtype, w);
2011 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002012cleanup:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002013 if (err->text != NULL) {
2014 PyObject_FREE(err->text);
2015 err->text = NULL;
2016 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002017}
2018
2019/* Print fatal error message and abort */
2020
2021void
Tim Peters7c321a82002-07-09 02:57:01 +00002022Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002023{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002024 fprintf(stderr, "Fatal Python error: %s\n", msg);
2025 fflush(stderr); /* it helps in Windows debug build */
2026 if (PyErr_Occurred()) {
Victor Stinner93362d42010-06-08 21:05:20 +00002027 PyErr_PrintEx(0);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002028 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002029#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002030 {
2031 size_t len = strlen(msg);
2032 WCHAR* buffer;
2033 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002034
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002035 /* Convert the message to wchar_t. This uses a simple one-to-one
2036 conversion, assuming that the this error message actually uses ASCII
2037 only. If this ceases to be true, we will have to convert. */
2038 buffer = alloca( (len+1) * (sizeof *buffer));
2039 for( i=0; i<=len; ++i)
2040 buffer[i] = msg[i];
2041 OutputDebugStringW(L"Fatal Python error: ");
2042 OutputDebugStringW(buffer);
2043 OutputDebugStringW(L"\n");
2044 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002045#ifdef _DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002046 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002047#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002048#endif /* MS_WINDOWS */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002049 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002050}
2051
2052/* Clean up and exit */
2053
Guido van Rossuma110aa61994-08-29 12:50:44 +00002054#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002055#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002056#endif
2057
Collin Winter670e6922007-03-21 02:57:17 +00002058static void (*pyexitfunc)(void) = NULL;
2059/* For the atexit module. */
2060void _Py_PyAtExit(void (*func)(void))
2061{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002062 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002063}
2064
2065static void
2066call_py_exitfuncs(void)
2067{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002068 if (pyexitfunc == NULL)
2069 return;
Collin Winter670e6922007-03-21 02:57:17 +00002070
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002071 (*pyexitfunc)();
2072 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002073}
2074
Antoine Pitroucefb3162009-10-20 22:08:36 +00002075/* Wait until threading._shutdown completes, provided
2076 the threading module was imported in the first place.
2077 The shutdown routine will wait until all non-daemon
2078 "threading" threads have completed. */
2079static void
2080wait_for_thread_shutdown(void)
2081{
2082#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002083 PyObject *result;
2084 PyThreadState *tstate = PyThreadState_GET();
2085 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2086 "threading");
2087 if (threading == NULL) {
2088 /* threading not imported */
2089 PyErr_Clear();
2090 return;
2091 }
2092 result = PyObject_CallMethod(threading, "_shutdown", "");
2093 if (result == NULL) {
2094 PyErr_WriteUnraisable(threading);
2095 }
2096 else {
2097 Py_DECREF(result);
2098 }
2099 Py_DECREF(threading);
Antoine Pitroucefb3162009-10-20 22:08:36 +00002100#endif
2101}
2102
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002103#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002104static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002105static int nexitfuncs = 0;
2106
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002107int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002108{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002109 if (nexitfuncs >= NEXITFUNCS)
2110 return -1;
2111 exitfuncs[nexitfuncs++] = func;
2112 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002113}
2114
Guido van Rossumcc283f51997-08-05 02:22:03 +00002115static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002116call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002117{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002118 while (nexitfuncs > 0)
2119 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002120
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002121 fflush(stdout);
2122 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002123}
2124
2125void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002126Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002127{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002128 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002129
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002130 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002131}
2132
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002133static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002134initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002135{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002136#ifdef SIGPIPE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002137 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002138#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002139#ifdef SIGXFZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002140 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002141#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002142#ifdef SIGXFSZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002143 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002144#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002145 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002146}
2147
Guido van Rossum7433b121997-02-14 19:45:36 +00002148
2149/*
2150 * The file descriptor fd is considered ``interactive'' if either
2151 * a) isatty(fd) is TRUE, or
2152 * b) the -i flag was given, and the filename associated with
2153 * the descriptor is NULL or "<stdin>" or "???".
2154 */
2155int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002156Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002157{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002158 if (isatty((int)fileno(fp)))
2159 return 1;
2160 if (!Py_InteractiveFlag)
2161 return 0;
2162 return (filename == NULL) ||
2163 (strcmp(filename, "<stdin>") == 0) ||
2164 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002165}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002166
2167
Tim Petersd08e3822003-04-17 15:24:21 +00002168#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002169#if defined(WIN32) && defined(_MSC_VER)
2170
2171/* Stack checking for Microsoft C */
2172
2173#include <malloc.h>
2174#include <excpt.h>
2175
Fred Drakee8de31c2000-08-31 05:38:39 +00002176/*
2177 * Return non-zero when we run out of memory on the stack; zero otherwise.
2178 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002179int
Fred Drake399739f2000-08-31 05:52:44 +00002180PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002181{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002182 __try {
2183 /* alloca throws a stack overflow exception if there's
2184 not enough space left on the stack */
2185 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2186 return 0;
2187 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2188 EXCEPTION_EXECUTE_HANDLER :
2189 EXCEPTION_CONTINUE_SEARCH) {
2190 int errcode = _resetstkoflw();
2191 if (errcode == 0)
2192 {
2193 Py_FatalError("Could not reset the stack!");
2194 }
2195 }
2196 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002197}
2198
2199#endif /* WIN32 && _MSC_VER */
2200
2201/* Alternate implementations can be added here... */
2202
2203#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002204
2205
2206/* Wrappers around sigaction() or signal(). */
2207
2208PyOS_sighandler_t
2209PyOS_getsig(int sig)
2210{
2211#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002212 struct sigaction context;
2213 if (sigaction(sig, NULL, &context) == -1)
2214 return SIG_ERR;
2215 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002216#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002217 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002218/* Special signal handling for the secure CRT in Visual Studio 2005 */
2219#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002220 switch (sig) {
2221 /* Only these signals are valid */
2222 case SIGINT:
2223 case SIGILL:
2224 case SIGFPE:
2225 case SIGSEGV:
2226 case SIGTERM:
2227 case SIGBREAK:
2228 case SIGABRT:
2229 break;
2230 /* Don't call signal() with other values or it will assert */
2231 default:
2232 return SIG_ERR;
2233 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002234#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002235 handler = signal(sig, SIG_IGN);
2236 if (handler != SIG_ERR)
2237 signal(sig, handler);
2238 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002239#endif
2240}
2241
2242PyOS_sighandler_t
2243PyOS_setsig(int sig, PyOS_sighandler_t handler)
2244{
2245#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002246 /* Some code in Modules/signalmodule.c depends on sigaction() being
2247 * used here if HAVE_SIGACTION is defined. Fix that if this code
2248 * changes to invalidate that assumption.
2249 */
2250 struct sigaction context, ocontext;
2251 context.sa_handler = handler;
2252 sigemptyset(&context.sa_mask);
2253 context.sa_flags = 0;
2254 if (sigaction(sig, &context, &ocontext) == -1)
2255 return SIG_ERR;
2256 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002257#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002258 PyOS_sighandler_t oldhandler;
2259 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002260#ifdef HAVE_SIGINTERRUPT
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002261 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002262#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002263 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002264#endif
2265}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002266
2267/* Deprecated C API functions still provided for binary compatiblity */
2268
2269#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002270PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002271PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2272{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002273 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274}
2275
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002276#undef PyParser_SimpleParseString
2277PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278PyParser_SimpleParseString(const char *str, int start)
2279{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002280 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002281}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002282
2283#undef PyRun_AnyFile
2284PyAPI_FUNC(int)
2285PyRun_AnyFile(FILE *fp, const char *name)
2286{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002287 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002288}
2289
2290#undef PyRun_AnyFileEx
2291PyAPI_FUNC(int)
2292PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2293{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002294 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002295}
2296
2297#undef PyRun_AnyFileFlags
2298PyAPI_FUNC(int)
2299PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2300{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002301 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002302}
2303
2304#undef PyRun_File
2305PyAPI_FUNC(PyObject *)
2306PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2307{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002308 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002309}
2310
2311#undef PyRun_FileEx
2312PyAPI_FUNC(PyObject *)
2313PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2314{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002315 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002316}
2317
2318#undef PyRun_FileFlags
2319PyAPI_FUNC(PyObject *)
2320PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002321 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002322{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002323 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002324}
2325
2326#undef PyRun_SimpleFile
2327PyAPI_FUNC(int)
2328PyRun_SimpleFile(FILE *f, const char *p)
2329{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002330 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002331}
2332
2333#undef PyRun_SimpleFileEx
2334PyAPI_FUNC(int)
2335PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2336{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002337 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002338}
2339
2340
2341#undef PyRun_String
2342PyAPI_FUNC(PyObject *)
2343PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2344{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002345 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002346}
2347
2348#undef PyRun_SimpleString
2349PyAPI_FUNC(int)
2350PyRun_SimpleString(const char *s)
2351{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002352 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002353}
2354
2355#undef Py_CompileString
2356PyAPI_FUNC(PyObject *)
2357Py_CompileString(const char *str, const char *p, int s)
2358{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002359 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002360}
2361
2362#undef PyRun_InteractiveOne
2363PyAPI_FUNC(int)
2364PyRun_InteractiveOne(FILE *f, const char *p)
2365{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002366 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002367}
2368
2369#undef PyRun_InteractiveLoop
2370PyAPI_FUNC(int)
2371PyRun_InteractiveLoop(FILE *f, const char *p)
2372{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002373 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002374}
2375
2376#ifdef __cplusplus
2377}
2378#endif