blob: 3031aef5f2b920f31f5f0573aee294e8840d9070 [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 Pitrou011bd622009-10-20 21:52:47 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +000064 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000065static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrou011bd622009-10-20 21:52:47 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000140 char* codeset;
141 PyObject *codec, *name;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143 codeset = nl_langinfo(CODESET);
144 if (!codeset || codeset[0] == '\0')
145 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 codec = _PyCodec_Lookup(codeset);
148 if (!codec)
149 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000156 codeset = strdup(_PyUnicode_AsString(name));
157 Py_DECREF(name);
158 return codeset;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000159
160error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000175 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000176#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 if (initialized)
180 return;
181 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000182
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000183#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000208 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (!_PyFrame_Init())
211 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (!_PyLong_Init())
214 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 if (!PyByteArray_Init())
217 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000228 /* Init Unicode implementation; relies on the codec registry */
229 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000240 /* initialize builtin exceptions */
241 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +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 Pitrouf95a1b32010-05-09 15:52:27 +0000263 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000266
Martin v. Löwis011e8422009-05-05 04:43:17 +0000267#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 /* On Unix, set the file system encoding according to the
269 user's preference, if the CODESET names a well-known
270 Python codec, and Py_FileSystemDefaultEncoding isn't
271 initialized by other means. Also set the encoding of
272 stdin and stdout if these are terminals. */
Martin v. Löwis011e8422009-05-05 04:43:17 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 codeset = get_codeset();
275 if (codeset) {
276 if (!Py_FileSystemDefaultEncoding)
277 Py_FileSystemDefaultEncoding = codeset;
278 else
279 free(codeset);
280 }
Martin v. Löwis011e8422009-05-05 04:43:17 +0000281#endif
282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if (install_sigs)
284 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 /* Initialize warnings. */
287 _PyWarnings_Init();
288 if (PySys_HasWarnOptions()) {
289 PyObject *warnings_module = PyImport_ImportModule("warnings");
290 if (!warnings_module)
291 PyErr_Clear();
292 Py_XDECREF(warnings_module);
293 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 initmain(); /* Module __main__ */
296 if (initstdio() < 0)
297 Py_FatalError(
298 "Py_Initialize: can't initialize sys standard streams");
299
300 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000301#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000303#endif /* WITH_THREAD */
Victor Stinner52f6dd72010-03-12 14:45:56 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (!Py_NoSiteFlag)
306 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307}
308
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000309void
310Py_Initialize(void)
311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000313}
314
315
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000316#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000317extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000318#endif
319
Guido van Rossume8432ac2007-07-09 15:04:50 +0000320/* Flush stdout and stderr */
321
Neal Norwitz2bad9702007-08-27 06:19:22 +0000322static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000323flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 PyObject *fout = PySys_GetObject("stdout");
326 PyObject *ferr = PySys_GetObject("stderr");
327 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (fout != NULL && fout != Py_None) {
330 tmp = PyObject_CallMethod(fout, "flush", "");
331 if (tmp == NULL)
332 PyErr_Clear();
333 else
334 Py_DECREF(tmp);
335 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000336
Victor Stinner9467b212010-05-14 00:59:09 +0000337 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 tmp = PyObject_CallMethod(ferr, "flush", "");
339 if (tmp == NULL)
340 PyErr_Clear();
341 else
342 Py_DECREF(tmp);
343 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000344}
345
Guido van Rossum25ce5661997-08-02 03:10:38 +0000346/* Undo the effect of Py_Initialize().
347
348 Beware: if multiple interpreter and/or thread states exist, these
349 are not wiped out; only the current thread and interpreter state
350 are deleted. But since everything else is deleted, those other
351 interpreter and thread states should no longer be used.
352
353 (XXX We should do better, e.g. wipe out all interpreters and
354 threads.)
355
356 Locking: as above.
357
358*/
359
360void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000361Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 PyInterpreterState *interp;
364 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (!initialized)
367 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 /* The interpreter is still entirely intact at this point, and the
372 * exit funcs may be relying on that. In particular, if some thread
373 * or exit func is still waiting to do an import, the import machinery
374 * expects Py_IsInitialized() to return true. So don't say the
375 * interpreter is uninitialized until after the exit funcs have run.
376 * Note that Threading.py uses an exit func to do a join on all the
377 * threads created thru it, so this also protects pending imports in
378 * the threads created via Threading.
379 */
380 call_py_exitfuncs();
381 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 /* Flush stdout+stderr */
384 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 /* Get current thread state and interpreter pointer */
387 tstate = PyThreadState_GET();
388 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 /* Disable signal handling */
391 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* Clear type lookup cache */
394 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 /* Collect garbage. This may call finalizers; it's nice to call these
397 * before all modules are destroyed.
398 * XXX If a __del__ or weakref callback is triggered here, and tries to
399 * XXX import a module, bad things can happen, because Python no
400 * XXX longer believes it's initialized.
401 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
402 * XXX is easy to provoke that way. I've also seen, e.g.,
403 * XXX Exception exceptions.ImportError: 'No module named sha'
404 * XXX in <function callback at 0x008F5718> ignored
405 * XXX but I'm unclear on exactly how that one happens. In any case,
406 * XXX I haven't seen a real-life report of either of these.
407 */
408 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000409#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 /* With COUNT_ALLOCS, it helps to run GC multiple times:
411 each collection might release some types from the type
412 list, so they become garbage. */
413 while (PyGC_Collect() > 0)
414 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000415#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 /* Destroy all modules */
418 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 /* Flush stdout+stderr (again, in case more was printed) */
421 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 /* Collect final garbage. This disposes of cycles created by
424 * new-style class definitions, for example.
425 * XXX This is disabled because it caused too many problems. If
426 * XXX a __del__ or weakref callback triggers here, Python code has
427 * XXX a hard time running, because even the sys module has been
428 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
429 * XXX One symptom is a sequence of information-free messages
430 * XXX coming from threads (if a __del__ or callback is invoked,
431 * XXX other threads can execute too, and any exception they encounter
432 * XXX triggers a comedy of errors as subsystem after subsystem
433 * XXX fails to find what it *expects* to find in sys to help report
434 * XXX the exception and consequent unexpected failures). I've also
435 * XXX seen segfaults then, after adding print statements to the
436 * XXX Python code getting called.
437 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000438#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000440#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
443 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000446#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000448#endif
449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000451
Tim Peters9cf25ce2003-04-17 15:21:01 +0000452#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* Display all objects still alive -- this can invoke arbitrary
454 * __repr__ overrides, so requires a mostly-intact interpreter.
455 * Alas, a lot of stuff may still be alive now that will be cleaned
456 * up later.
457 */
458 if (Py_GETENV("PYTHONDUMPREFS"))
459 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000460#endif /* Py_TRACE_REFS */
461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 /* Clear interpreter state */
463 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* Now we decref the exception classes. After this point nothing
466 can raise an exception. That's okay, because each Fini() method
467 below has been checked to make sure no exceptions are ever
468 raised.
469 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000474#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000476#endif /* WITH_THREAD */
477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* Delete current thread */
479 PyThreadState_Swap(NULL);
480 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 /* Sundry finalizers */
483 PyMethod_Fini();
484 PyFrame_Fini();
485 PyCFunction_Fini();
486 PyTuple_Fini();
487 PyList_Fini();
488 PySet_Fini();
489 PyBytes_Fini();
490 PyByteArray_Fini();
491 PyLong_Fini();
492 PyFloat_Fini();
493 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* Cleanup Unicode implementation */
496 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 /* reset file system default encoding */
499 if (!Py_HasFileSystemDefaultEncoding) {
500 free((char*)Py_FileSystemDefaultEncoding);
501 Py_FileSystemDefaultEncoding = NULL;
502 }
Christian Heimesc8967002007-11-30 10:18:26 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 /* XXX Still allocated:
505 - various static ad-hoc pointers to interned strings
506 - int and float free list blocks
507 - whatever various modules and libraries allocate
508 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000511
Tim Peters269b2a62003-04-17 19:52:29 +0000512#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 /* Display addresses (& refcnts) of all objects still alive.
514 * An address can be used to find the repr of the object, printed
515 * above by _Py_PrintReferences.
516 */
517 if (Py_GETENV("PYTHONDUMPREFS"))
518 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000519#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000520#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (Py_GETENV("PYTHONMALLOCSTATS"))
522 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000523#endif
524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000526}
527
528/* Create and initialize a new interpreter and thread, and return the
529 new thread. This requires that Py_Initialize() has been called
530 first.
531
532 Unsuccessful initialization yields a NULL pointer. Note that *no*
533 exception information is available even in this case -- the
534 exception information is held in the thread, and there is no
535 thread.
536
537 Locking: as above.
538
539*/
540
541PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000542Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 PyInterpreterState *interp;
545 PyThreadState *tstate, *save_tstate;
546 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (!initialized)
549 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 interp = PyInterpreterState_New();
552 if (interp == NULL)
553 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 tstate = PyThreadState_New(interp);
556 if (tstate == NULL) {
557 PyInterpreterState_Delete(interp);
558 return NULL;
559 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 interp->modules = PyDict_New();
566 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 bimod = _PyImport_FindExtension("builtins", "builtins");
569 if (bimod != NULL) {
570 interp->builtins = PyModule_GetDict(bimod);
571 if (interp->builtins == NULL)
572 goto handle_error;
573 Py_INCREF(interp->builtins);
574 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 /* initialize builtin exceptions */
577 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 sysmod = _PyImport_FindExtension("sys", "sys");
580 if (bimod != NULL && sysmod != NULL) {
581 PyObject *pstderr;
582 interp->sysdict = PyModule_GetDict(sysmod);
583 if (interp->sysdict == NULL)
584 goto handle_error;
585 Py_INCREF(interp->sysdict);
586 PySys_SetPath(Py_GetPath());
587 PyDict_SetItemString(interp->sysdict, "modules",
588 interp->modules);
589 /* Set up a preliminary stderr printer until we have enough
590 infrastructure for the io module in place. */
591 pstderr = PyFile_NewStdPrinter(fileno(stderr));
592 if (pstderr == NULL)
593 Py_FatalError("Py_Initialize: can't set preliminary stderr");
594 PySys_SetObject("stderr", pstderr);
595 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 _PyImportHooks_Init();
598 if (initstdio() < 0)
599 Py_FatalError(
600 "Py_Initialize: can't initialize sys standard streams");
601 initmain();
602 if (!Py_NoSiteFlag)
603 initsite();
604 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (!PyErr_Occurred())
607 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608
Thomas Wouters89f507f2006-12-13 04:49:30 +0000609handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyErr_Print();
613 PyThreadState_Clear(tstate);
614 PyThreadState_Swap(save_tstate);
615 PyThreadState_Delete(tstate);
616 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000619}
620
621/* Delete an interpreter and its last thread. This requires that the
622 given thread state is current, that the thread has no remaining
623 frames, and that it is its interpreter's only remaining thread.
624 It is a fatal error to violate these constraints.
625
626 (Py_Finalize() doesn't have these constraints -- it zaps
627 everything, regardless.)
628
629 Locking: as above.
630
631*/
632
633void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000634Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 if (tstate != PyThreadState_GET())
639 Py_FatalError("Py_EndInterpreter: thread is not current");
640 if (tstate->frame != NULL)
641 Py_FatalError("Py_EndInterpreter: thread still has a frame");
642 if (tstate != interp->tstate_head || tstate->next != NULL)
643 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyImport_Cleanup();
646 PyInterpreterState_Clear(interp);
647 PyThreadState_Swap(NULL);
648 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000649}
650
Martin v. Löwis790465f2008-04-05 20:41:37 +0000651static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000652
653void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000654Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (pn && *pn)
657 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000658}
659
Martin v. Löwis790465f2008-04-05 20:41:37 +0000660wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000661Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000664}
665
Martin v. Löwis790465f2008-04-05 20:41:37 +0000666static wchar_t *default_home = NULL;
667static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000668
669void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000670Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000673}
674
Martin v. Löwis790465f2008-04-05 20:41:37 +0000675wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000676Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 wchar_t *home = default_home;
679 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
680 char* chome = Py_GETENV("PYTHONHOME");
681 if (chome) {
682 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
683 if (r != (size_t)-1 && r <= PATH_MAX)
684 home = env_home;
685 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 }
688 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000689}
690
Guido van Rossum6135a871995-01-09 17:53:26 +0000691/* Create __main__ module */
692
693static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000694initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyObject *m, *d;
697 m = PyImport_AddModule("__main__");
698 if (m == NULL)
699 Py_FatalError("can't create __main__ module");
700 d = PyModule_GetDict(m);
701 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
702 PyObject *bimod = PyImport_ImportModule("builtins");
703 if (bimod == NULL ||
704 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
705 Py_FatalError("can't add __builtins__ to __main__");
706 Py_DECREF(bimod);
707 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000708}
709
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000710/* Import the site module (not into __main__ though) */
711
712static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000713initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyObject *m;
716 m = PyImport_ImportModule("site");
717 if (m == NULL) {
718 PyErr_Print();
719 Py_Finalize();
720 exit(1);
721 }
722 else {
723 Py_DECREF(m);
724 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000725}
726
Antoine Pitrou05608432009-01-09 18:53:14 +0000727static PyObject*
728create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 int fd, int write_mode, char* name,
730 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
733 const char* mode;
734 PyObject *line_buffering;
735 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 /* stdin is always opened in buffered mode, first because it shouldn't
738 make a difference in common use cases, second because TextIOWrapper
739 depends on the presence of a read1() method which only exists on
740 buffered streams.
741 */
742 if (Py_UnbufferedStdioFlag && write_mode)
743 buffering = 0;
744 else
745 buffering = -1;
746 if (write_mode)
747 mode = "wb";
748 else
749 mode = "rb";
750 buf = PyObject_CallMethod(io, "open", "isiOOOi",
751 fd, mode, buffering,
752 Py_None, Py_None, Py_None, 0);
753 if (buf == NULL)
754 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (buffering) {
757 raw = PyObject_GetAttrString(buf, "raw");
758 if (raw == NULL)
759 goto error;
760 }
761 else {
762 raw = buf;
763 Py_INCREF(raw);
764 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 text = PyUnicode_FromString(name);
767 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
768 goto error;
769 res = PyObject_CallMethod(raw, "isatty", "");
770 if (res == NULL)
771 goto error;
772 isatty = PyObject_IsTrue(res);
773 Py_DECREF(res);
774 if (isatty == -1)
775 goto error;
776 if (isatty || Py_UnbufferedStdioFlag)
777 line_buffering = Py_True;
778 else
779 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 Py_CLEAR(raw);
782 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
785 buf, encoding, errors,
786 "\n", line_buffering);
787 Py_CLEAR(buf);
788 if (stream == NULL)
789 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (write_mode)
792 mode = "w";
793 else
794 mode = "r";
795 text = PyUnicode_FromString(mode);
796 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
797 goto error;
798 Py_CLEAR(text);
799 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000800
801error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 Py_XDECREF(buf);
803 Py_XDECREF(stream);
804 Py_XDECREF(text);
805 Py_XDECREF(raw);
806 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000807}
808
Georg Brandl1a3284e2007-12-02 09:40:06 +0000809/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000810static int
811initstdio(void)
812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PyObject *iomod = NULL, *wrapper;
814 PyObject *bimod = NULL;
815 PyObject *m;
816 PyObject *std = NULL;
817 int status = 0, fd;
818 PyObject * encoding_attr;
819 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 /* Hack to avoid a nasty recursion issue when Python is invoked
822 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
823 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
824 goto error;
825 }
826 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
829 goto error;
830 }
831 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 if (!(bimod = PyImport_ImportModule("builtins"))) {
834 goto error;
835 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (!(iomod = PyImport_ImportModule("io"))) {
838 goto error;
839 }
840 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
841 goto error;
842 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 /* Set builtins.open */
845 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
846 goto error;
847 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 encoding = Py_GETENV("PYTHONIOENCODING");
850 errors = NULL;
851 if (encoding) {
852 encoding = strdup(encoding);
853 errors = strchr(encoding, ':');
854 if (errors) {
855 *errors = '\0';
856 errors++;
857 }
858 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 /* Set sys.stdin */
861 fd = fileno(stdin);
862 /* Under some conditions stdin, stdout and stderr may not be connected
863 * and fileno() may point to an invalid file descriptor. For example
864 * GUI apps don't have valid standard streams by default.
865 */
866 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000867#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 std = Py_None;
869 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000870#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000872#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 }
874 else {
875 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
876 if (std == NULL)
877 goto error;
878 } /* if (fd < 0) */
879 PySys_SetObject("__stdin__", std);
880 PySys_SetObject("stdin", std);
881 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000882
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 /* Set sys.stdout */
884 fd = fileno(stdout);
885 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000886#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 std = Py_None;
888 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000889#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000891#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 }
893 else {
894 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
895 if (std == NULL)
896 goto error;
897 } /* if (fd < 0) */
898 PySys_SetObject("__stdout__", std);
899 PySys_SetObject("stdout", std);
900 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000901
Guido van Rossum98297ee2007-11-06 21:34:58 +0000902#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 /* Set sys.stderr, replaces the preliminary stderr */
904 fd = fileno(stderr);
905 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000906#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 std = Py_None;
908 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000909#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000911#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 }
913 else {
914 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
915 if (std == NULL)
916 goto error;
917 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 /* Same as hack above, pre-import stderr's codec to avoid recursion
920 when import.c tries to write to stderr in verbose mode. */
921 encoding_attr = PyObject_GetAttrString(std, "encoding");
922 if (encoding_attr != NULL) {
923 const char * encoding;
924 encoding = _PyUnicode_AsString(encoding_attr);
925 if (encoding != NULL) {
926 _PyCodec_Lookup(encoding);
927 }
928 }
929 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PySys_SetObject("__stderr__", std);
932 PySys_SetObject("stderr", std);
933 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000934#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000937 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 status = -1;
939 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (encoding)
942 free(encoding);
943 Py_XDECREF(bimod);
944 Py_XDECREF(iomod);
945 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000946}
947
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000948/* Parse input from a file and execute it */
949
950int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000951PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000953{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (filename == NULL)
955 filename = "???";
956 if (Py_FdIsInteractive(fp, filename)) {
957 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
958 if (closeit)
959 fclose(fp);
960 return err;
961 }
962 else
963 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000964}
965
966int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000967PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 PyObject *v;
970 int ret;
971 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 if (flags == NULL) {
974 flags = &local_flags;
975 local_flags.cf_flags = 0;
976 }
977 v = PySys_GetObject("ps1");
978 if (v == NULL) {
979 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
980 Py_XDECREF(v);
981 }
982 v = PySys_GetObject("ps2");
983 if (v == NULL) {
984 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
985 Py_XDECREF(v);
986 }
987 for (;;) {
988 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
989 PRINT_TOTAL_REFS();
990 if (ret == E_EOF)
991 return 0;
992 /*
993 if (ret == E_NOMEM)
994 return -1;
995 */
996 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000997}
998
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000999/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001000static int PARSER_FLAGS(PyCompilerFlags *flags)
1001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 int parser_flags = 0;
1003 if (!flags)
1004 return 0;
1005 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1006 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1007 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1008 parser_flags |= PyPARSE_IGNORE_COOKIE;
1009 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1010 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1011 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001012}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001013
Thomas Wouters89f507f2006-12-13 04:49:30 +00001014#if 0
1015/* Keep an example of flags with future keyword support. */
1016#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1018 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1019 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1020 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001021#endif
1022
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001023int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001024PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 PyObject *m, *d, *v, *w, *oenc = NULL;
1027 mod_ty mod;
1028 PyArena *arena;
1029 char *ps1 = "", *ps2 = "", *enc = NULL;
1030 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 if (fp == stdin) {
1033 /* Fetch encoding from sys.stdin */
1034 v = PySys_GetObject("stdin");
1035 if (v == NULL || v == Py_None)
1036 return -1;
1037 oenc = PyObject_GetAttrString(v, "encoding");
1038 if (!oenc)
1039 return -1;
1040 enc = _PyUnicode_AsString(oenc);
1041 }
1042 v = PySys_GetObject("ps1");
1043 if (v != NULL) {
1044 v = PyObject_Str(v);
1045 if (v == NULL)
1046 PyErr_Clear();
1047 else if (PyUnicode_Check(v))
1048 ps1 = _PyUnicode_AsString(v);
1049 }
1050 w = PySys_GetObject("ps2");
1051 if (w != NULL) {
1052 w = PyObject_Str(w);
1053 if (w == NULL)
1054 PyErr_Clear();
1055 else if (PyUnicode_Check(w))
1056 ps2 = _PyUnicode_AsString(w);
1057 }
1058 arena = PyArena_New();
1059 if (arena == NULL) {
1060 Py_XDECREF(v);
1061 Py_XDECREF(w);
1062 Py_XDECREF(oenc);
1063 return -1;
1064 }
1065 mod = PyParser_ASTFromFile(fp, filename, enc,
1066 Py_single_input, ps1, ps2,
1067 flags, &errcode, arena);
1068 Py_XDECREF(v);
1069 Py_XDECREF(w);
1070 Py_XDECREF(oenc);
1071 if (mod == NULL) {
1072 PyArena_Free(arena);
1073 if (errcode == E_EOF) {
1074 PyErr_Clear();
1075 return E_EOF;
1076 }
1077 PyErr_Print();
1078 return -1;
1079 }
1080 m = PyImport_AddModule("__main__");
1081 if (m == NULL) {
1082 PyArena_Free(arena);
1083 return -1;
1084 }
1085 d = PyModule_GetDict(m);
1086 v = run_mod(mod, filename, d, d, flags, arena);
1087 PyArena_Free(arena);
1088 flush_io();
1089 if (v == NULL) {
1090 PyErr_Print();
1091 return -1;
1092 }
1093 Py_DECREF(v);
1094 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001095}
1096
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001097/* Check whether a file maybe a pyc file: Look at the extension,
1098 the file type, and, if we may close it, at the first few bytes. */
1099
1100static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001101maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1104 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 /* Only look into the file if we are allowed to close it, since
1107 it then should also be seekable. */
1108 if (closeit) {
1109 /* Read only two bytes of the magic. If the file was opened in
1110 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1111 be read as they are on disk. */
1112 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1113 unsigned char buf[2];
1114 /* Mess: In case of -x, the stream is NOT at its start now,
1115 and ungetc() was used to push back the first newline,
1116 which makes the current stream position formally undefined,
1117 and a x-platform nightmare.
1118 Unfortunately, we have no direct way to know whether -x
1119 was specified. So we use a terrible hack: if the current
1120 stream position is not 0, we assume -x was specified, and
1121 give up. Bug 132850 on SourceForge spells out the
1122 hopelessness of trying anything else (fseek and ftell
1123 don't work predictably x-platform for text-mode files).
1124 */
1125 int ispyc = 0;
1126 if (ftell(fp) == 0) {
1127 if (fread(buf, 1, 2, fp) == 2 &&
1128 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1129 ispyc = 1;
1130 rewind(fp);
1131 }
1132 return ispyc;
1133 }
1134 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001135}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001136
Guido van Rossum0df002c2000-08-27 19:21:52 +00001137int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001138PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PyObject *m, *d, *v;
1142 const char *ext;
1143 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 m = PyImport_AddModule("__main__");
1146 if (m == NULL)
1147 return -1;
1148 d = PyModule_GetDict(m);
1149 if (PyDict_GetItemString(d, "__file__") == NULL) {
1150 PyObject *f;
1151 f = PyUnicode_DecodeFSDefault(filename);
1152 if (f == NULL)
1153 return -1;
1154 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1155 Py_DECREF(f);
1156 return -1;
1157 }
1158 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1159 return -1;
1160 set_file_name = 1;
1161 Py_DECREF(f);
1162 }
1163 len = strlen(filename);
1164 ext = filename + len - (len > 4 ? 4 : 0);
1165 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1166 /* Try to run a pyc file. First, re-open in binary */
1167 if (closeit)
1168 fclose(fp);
1169 if ((fp = fopen(filename, "rb")) == NULL) {
1170 fprintf(stderr, "python: Can't reopen .pyc file\n");
1171 ret = -1;
1172 goto done;
1173 }
1174 /* Turn on optimization if a .pyo file is given */
1175 if (strcmp(ext, ".pyo") == 0)
1176 Py_OptimizeFlag = 1;
1177 v = run_pyc_file(fp, filename, d, d, flags);
1178 } else {
1179 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1180 closeit, flags);
1181 }
1182 flush_io();
1183 if (v == NULL) {
1184 PyErr_Print();
1185 ret = -1;
1186 goto done;
1187 }
1188 Py_DECREF(v);
1189 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001190 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1192 PyErr_Clear();
1193 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001194}
1195
1196int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001197PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyObject *m, *d, *v;
1200 m = PyImport_AddModule("__main__");
1201 if (m == NULL)
1202 return -1;
1203 d = PyModule_GetDict(m);
1204 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1205 if (v == NULL) {
1206 PyErr_Print();
1207 return -1;
1208 }
1209 Py_DECREF(v);
1210 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001211}
1212
Barry Warsaw035574d1997-08-29 22:07:17 +00001213static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001214parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 long hold;
1218 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 /* old style errors */
1221 if (PyTuple_Check(err))
1222 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1223 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (! (v = PyObject_GetAttrString(err, "msg")))
1228 goto finally;
1229 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (!(v = PyObject_GetAttrString(err, "filename")))
1232 goto finally;
1233 if (v == Py_None)
1234 *filename = NULL;
1235 else if (! (*filename = _PyUnicode_AsString(v)))
1236 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 Py_DECREF(v);
1239 if (!(v = PyObject_GetAttrString(err, "lineno")))
1240 goto finally;
1241 hold = PyLong_AsLong(v);
1242 Py_DECREF(v);
1243 v = NULL;
1244 if (hold < 0 && PyErr_Occurred())
1245 goto finally;
1246 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (!(v = PyObject_GetAttrString(err, "offset")))
1249 goto finally;
1250 if (v == Py_None) {
1251 *offset = -1;
1252 Py_DECREF(v);
1253 v = NULL;
1254 } else {
1255 hold = PyLong_AsLong(v);
1256 Py_DECREF(v);
1257 v = NULL;
1258 if (hold < 0 && PyErr_Occurred())
1259 goto finally;
1260 *offset = (int)hold;
1261 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (!(v = PyObject_GetAttrString(err, "text")))
1264 goto finally;
1265 if (v == Py_None)
1266 *text = NULL;
1267 else if (!PyUnicode_Check(v) ||
1268 !(*text = _PyUnicode_AsString(v)))
1269 goto finally;
1270 Py_DECREF(v);
1271 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001272
1273finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 Py_XDECREF(v);
1275 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001276}
1277
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001278void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001279PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001282}
1283
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001284static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001285print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 char *nl;
1288 if (offset >= 0) {
1289 if (offset > 0 && offset == (int)strlen(text))
1290 offset--;
1291 for (;;) {
1292 nl = strchr(text, '\n');
1293 if (nl == NULL || nl-text >= offset)
1294 break;
1295 offset -= (int)(nl+1-text);
1296 text = nl+1;
1297 }
1298 while (*text == ' ' || *text == '\t') {
1299 text++;
1300 offset--;
1301 }
1302 }
1303 PyFile_WriteString(" ", f);
1304 PyFile_WriteString(text, f);
1305 if (*text == '\0' || text[strlen(text)-1] != '\n')
1306 PyFile_WriteString("\n", f);
1307 if (offset == -1)
1308 return;
1309 PyFile_WriteString(" ", f);
1310 offset--;
1311 while (offset > 0) {
1312 PyFile_WriteString(" ", f);
1313 offset--;
1314 }
1315 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001316}
1317
Guido van Rossum66e8e862001-03-23 17:54:43 +00001318static void
1319handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 PyObject *exception, *value, *tb;
1322 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 if (Py_InspectFlag)
1325 /* Don't exit if -i flag was given. This flag is set to 0
1326 * when entering interactive mode for inspecting. */
1327 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 PyErr_Fetch(&exception, &value, &tb);
1330 fflush(stdout);
1331 if (value == NULL || value == Py_None)
1332 goto done;
1333 if (PyExceptionInstance_Check(value)) {
1334 /* The error code should be in the `code' attribute. */
1335 PyObject *code = PyObject_GetAttrString(value, "code");
1336 if (code) {
1337 Py_DECREF(value);
1338 value = code;
1339 if (value == Py_None)
1340 goto done;
1341 }
1342 /* If we failed to dig out the 'code' attribute,
1343 just let the else clause below print the error. */
1344 }
1345 if (PyLong_Check(value))
1346 exitcode = (int)PyLong_AsLong(value);
1347 else {
1348 PyObject_Print(value, stderr, Py_PRINT_RAW);
1349 PySys_WriteStderr("\n");
1350 exitcode = 1;
1351 }
Tim Peterscf615b52003-04-19 18:47:02 +00001352 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 /* Restore and clear the exception info, in order to properly decref
1354 * the exception, value, and traceback. If we just exit instead,
1355 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1356 * some finalizers from running.
1357 */
1358 PyErr_Restore(exception, value, tb);
1359 PyErr_Clear();
1360 Py_Exit(exitcode);
1361 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001362}
1363
1364void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001365PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1370 handle_system_exit();
1371 }
1372 PyErr_Fetch(&exception, &v, &tb);
1373 if (exception == NULL)
1374 return;
1375 PyErr_NormalizeException(&exception, &v, &tb);
1376 if (tb == NULL) {
1377 tb = Py_None;
1378 Py_INCREF(tb);
1379 }
1380 PyException_SetTraceback(v, tb);
1381 if (exception == NULL)
1382 return;
1383 /* Now we know v != NULL too */
1384 if (set_sys_last_vars) {
1385 PySys_SetObject("last_type", exception);
1386 PySys_SetObject("last_value", v);
1387 PySys_SetObject("last_traceback", tb);
1388 }
1389 hook = PySys_GetObject("excepthook");
1390 if (hook) {
1391 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1392 PyObject *result = PyEval_CallObject(hook, args);
1393 if (result == NULL) {
1394 PyObject *exception2, *v2, *tb2;
1395 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1396 handle_system_exit();
1397 }
1398 PyErr_Fetch(&exception2, &v2, &tb2);
1399 PyErr_NormalizeException(&exception2, &v2, &tb2);
1400 /* It should not be possible for exception2 or v2
1401 to be NULL. However PyErr_Display() can't
1402 tolerate NULLs, so just be safe. */
1403 if (exception2 == NULL) {
1404 exception2 = Py_None;
1405 Py_INCREF(exception2);
1406 }
1407 if (v2 == NULL) {
1408 v2 = Py_None;
1409 Py_INCREF(v2);
1410 }
1411 fflush(stdout);
1412 PySys_WriteStderr("Error in sys.excepthook:\n");
1413 PyErr_Display(exception2, v2, tb2);
1414 PySys_WriteStderr("\nOriginal exception was:\n");
1415 PyErr_Display(exception, v, tb);
1416 Py_DECREF(exception2);
1417 Py_DECREF(v2);
1418 Py_XDECREF(tb2);
1419 }
1420 Py_XDECREF(result);
1421 Py_XDECREF(args);
1422 } else {
1423 PySys_WriteStderr("sys.excepthook is missing\n");
1424 PyErr_Display(exception, v, tb);
1425 }
1426 Py_XDECREF(exception);
1427 Py_XDECREF(v);
1428 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001429}
1430
Benjamin Petersone6528212008-07-15 15:32:09 +00001431static void
1432print_exception(PyObject *f, PyObject *value)
1433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 int err = 0;
1435 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 if (!PyExceptionInstance_Check(value)) {
1438 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1439 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1440 PyFile_WriteString(" found\n", f);
1441 return;
1442 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 Py_INCREF(value);
1445 fflush(stdout);
1446 type = (PyObject *) Py_TYPE(value);
1447 tb = PyException_GetTraceback(value);
1448 if (tb && tb != Py_None)
1449 err = PyTraceBack_Print(tb, f);
1450 if (err == 0 &&
1451 PyObject_HasAttrString(value, "print_file_and_line"))
1452 {
1453 PyObject *message;
1454 const char *filename, *text;
1455 int lineno, offset;
1456 if (!parse_syntax_error(value, &message, &filename,
1457 &lineno, &offset, &text))
1458 PyErr_Clear();
1459 else {
1460 char buf[10];
1461 PyFile_WriteString(" File \"", f);
1462 if (filename == NULL)
1463 PyFile_WriteString("<string>", f);
1464 else
1465 PyFile_WriteString(filename, f);
1466 PyFile_WriteString("\", line ", f);
1467 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1468 PyFile_WriteString(buf, f);
1469 PyFile_WriteString("\n", f);
1470 if (text != NULL)
1471 print_error_text(f, offset, text);
1472 Py_DECREF(value);
1473 value = message;
1474 /* Can't be bothered to check all those
1475 PyFile_WriteString() calls */
1476 if (PyErr_Occurred())
1477 err = -1;
1478 }
1479 }
1480 if (err) {
1481 /* Don't do anything else */
1482 }
1483 else {
1484 PyObject* moduleName;
1485 char* className;
1486 assert(PyExceptionClass_Check(type));
1487 className = PyExceptionClass_Name(type);
1488 if (className != NULL) {
1489 char *dot = strrchr(className, '.');
1490 if (dot != NULL)
1491 className = dot+1;
1492 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 moduleName = PyObject_GetAttrString(type, "__module__");
1495 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1496 {
1497 Py_DECREF(moduleName);
1498 err = PyFile_WriteString("<unknown>", f);
1499 }
1500 else {
1501 char* modstr = _PyUnicode_AsString(moduleName);
1502 if (modstr && strcmp(modstr, "builtins"))
1503 {
1504 err = PyFile_WriteString(modstr, f);
1505 err += PyFile_WriteString(".", f);
1506 }
1507 Py_DECREF(moduleName);
1508 }
1509 if (err == 0) {
1510 if (className == NULL)
1511 err = PyFile_WriteString("<unknown>", f);
1512 else
1513 err = PyFile_WriteString(className, f);
1514 }
1515 }
1516 if (err == 0 && (value != Py_None)) {
1517 PyObject *s = PyObject_Str(value);
1518 /* only print colon if the str() of the
1519 object is not the empty string
1520 */
1521 if (s == NULL)
1522 err = -1;
1523 else if (!PyUnicode_Check(s) ||
1524 PyUnicode_GetSize(s) != 0)
1525 err = PyFile_WriteString(": ", f);
1526 if (err == 0)
1527 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1528 Py_XDECREF(s);
1529 }
1530 /* try to write a newline in any case */
1531 err += PyFile_WriteString("\n", f);
1532 Py_XDECREF(tb);
1533 Py_DECREF(value);
1534 /* If an error happened here, don't show it.
1535 XXX This is wrong, but too many callers rely on this behavior. */
1536 if (err != 0)
1537 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001538}
1539
1540static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 "\nThe above exception was the direct cause "
1542 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001543
1544static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 "\nDuring handling of the above exception, "
1546 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001547
1548static void
1549print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 int err = 0, res;
1552 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 if (seen != NULL) {
1555 /* Exception chaining */
1556 if (PySet_Add(seen, value) == -1)
1557 PyErr_Clear();
1558 else if (PyExceptionInstance_Check(value)) {
1559 cause = PyException_GetCause(value);
1560 context = PyException_GetContext(value);
1561 if (cause) {
1562 res = PySet_Contains(seen, cause);
1563 if (res == -1)
1564 PyErr_Clear();
1565 if (res == 0) {
1566 print_exception_recursive(
1567 f, cause, seen);
1568 err |= PyFile_WriteString(
1569 cause_message, f);
1570 }
1571 }
1572 else if (context) {
1573 res = PySet_Contains(seen, context);
1574 if (res == -1)
1575 PyErr_Clear();
1576 if (res == 0) {
1577 print_exception_recursive(
1578 f, context, seen);
1579 err |= PyFile_WriteString(
1580 context_message, f);
1581 }
1582 }
1583 Py_XDECREF(context);
1584 Py_XDECREF(cause);
1585 }
1586 }
1587 print_exception(f, value);
1588 if (err != 0)
1589 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001590}
1591
Thomas Wouters477c8d52006-05-27 19:21:47 +00001592void
1593PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 PyObject *seen;
1596 PyObject *f = PySys_GetObject("stderr");
1597 if (f == Py_None) {
1598 /* pass */
1599 }
1600 else if (f == NULL) {
1601 _PyObject_Dump(value);
1602 fprintf(stderr, "lost sys.stderr\n");
1603 }
1604 else {
1605 /* We choose to ignore seen being possibly NULL, and report
1606 at least the main exception (it could be a MemoryError).
1607 */
1608 seen = PySet_New(NULL);
1609 if (seen == NULL)
1610 PyErr_Clear();
1611 print_exception_recursive(f, value, seen);
1612 Py_XDECREF(seen);
1613 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001614}
1615
Guido van Rossum82598051997-03-05 00:20:32 +00001616PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001617PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 PyObject *ret = NULL;
1621 mod_ty mod;
1622 PyArena *arena = PyArena_New();
1623 if (arena == NULL)
1624 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1627 if (mod != NULL)
1628 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1629 PyArena_Free(arena);
1630 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001631}
1632
1633PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001634PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 PyObject *ret;
1638 mod_ty mod;
1639 PyArena *arena = PyArena_New();
1640 if (arena == NULL)
1641 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1644 flags, NULL, arena);
1645 if (closeit)
1646 fclose(fp);
1647 if (mod == NULL) {
1648 PyArena_Free(arena);
1649 return NULL;
1650 }
1651 ret = run_mod(mod, filename, globals, locals, flags, arena);
1652 PyArena_Free(arena);
1653 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001654}
1655
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001656static void
1657flush_io(void)
1658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 PyObject *f, *r;
1660 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 /* Save the current exception */
1663 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 f = PySys_GetObject("stderr");
1666 if (f != NULL) {
1667 r = PyObject_CallMethod(f, "flush", "");
1668 if (r)
1669 Py_DECREF(r);
1670 else
1671 PyErr_Clear();
1672 }
1673 f = PySys_GetObject("stdout");
1674 if (f != NULL) {
1675 r = PyObject_CallMethod(f, "flush", "");
1676 if (r)
1677 Py_DECREF(r);
1678 else
1679 PyErr_Clear();
1680 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001683}
1684
Guido van Rossum82598051997-03-05 00:20:32 +00001685static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001686run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 PyCodeObject *co;
1690 PyObject *v;
1691 co = PyAST_Compile(mod, filename, flags, arena);
1692 if (co == NULL)
1693 return NULL;
1694 v = PyEval_EvalCode(co, globals, locals);
1695 Py_DECREF(co);
1696 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001697}
1698
Guido van Rossum82598051997-03-05 00:20:32 +00001699static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001700run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 PyCodeObject *co;
1704 PyObject *v;
1705 long magic;
1706 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 magic = PyMarshal_ReadLongFromFile(fp);
1709 if (magic != PyImport_GetMagicNumber()) {
1710 PyErr_SetString(PyExc_RuntimeError,
1711 "Bad magic number in .pyc file");
1712 return NULL;
1713 }
1714 (void) PyMarshal_ReadLongFromFile(fp);
1715 v = PyMarshal_ReadLastObjectFromFile(fp);
1716 fclose(fp);
1717 if (v == NULL || !PyCode_Check(v)) {
1718 Py_XDECREF(v);
1719 PyErr_SetString(PyExc_RuntimeError,
1720 "Bad code object in .pyc file");
1721 return NULL;
1722 }
1723 co = (PyCodeObject *)v;
1724 v = PyEval_EvalCode(co, globals, locals);
1725 if (v && flags)
1726 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1727 Py_DECREF(co);
1728 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001729}
1730
Guido van Rossum82598051997-03-05 00:20:32 +00001731PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001732Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyCodeObject *co;
1736 mod_ty mod;
1737 PyArena *arena = PyArena_New();
1738 if (arena == NULL)
1739 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1742 if (mod == NULL) {
1743 PyArena_Free(arena);
1744 return NULL;
1745 }
1746 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1747 PyObject *result = PyAST_mod2obj(mod);
1748 PyArena_Free(arena);
1749 return result;
1750 }
1751 co = PyAST_Compile(mod, filename, flags, arena);
1752 PyArena_Free(arena);
1753 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001754}
1755
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001756struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001757Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 struct symtable *st;
1760 mod_ty mod;
1761 PyCompilerFlags flags;
1762 PyArena *arena = PyArena_New();
1763 if (arena == NULL)
1764 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 flags.cf_flags = 0;
1767 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1768 if (mod == NULL) {
1769 PyArena_Free(arena);
1770 return NULL;
1771 }
1772 st = PySymtable_Build(mod, filename, 0);
1773 PyArena_Free(arena);
1774 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001775}
1776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777/* Preferred access to parser is through AST. */
1778mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001779PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 mod_ty mod;
1783 PyCompilerFlags localflags;
1784 perrdetail err;
1785 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1788 &_PyParser_Grammar, start, &err,
1789 &iflags);
1790 if (flags == NULL) {
1791 localflags.cf_flags = 0;
1792 flags = &localflags;
1793 }
1794 if (n) {
1795 flags->cf_flags |= iflags & PyCF_MASK;
1796 mod = PyAST_FromNode(n, flags, filename, arena);
1797 PyNode_Free(n);
1798 return mod;
1799 }
1800 else {
1801 err_input(&err);
1802 return NULL;
1803 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804}
1805
1806mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001807PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 int start, char *ps1,
1809 char *ps2, PyCompilerFlags *flags, int *errcode,
1810 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 mod_ty mod;
1813 PyCompilerFlags localflags;
1814 perrdetail err;
1815 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1818 &_PyParser_Grammar,
1819 start, ps1, ps2, &err, &iflags);
1820 if (flags == NULL) {
1821 localflags.cf_flags = 0;
1822 flags = &localflags;
1823 }
1824 if (n) {
1825 flags->cf_flags |= iflags & PyCF_MASK;
1826 mod = PyAST_FromNode(n, flags, filename, arena);
1827 PyNode_Free(n);
1828 return mod;
1829 }
1830 else {
1831 err_input(&err);
1832 if (errcode)
1833 *errcode = err.error;
1834 return NULL;
1835 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836}
1837
Guido van Rossuma110aa61994-08-29 12:50:44 +00001838/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001839
Guido van Rossuma110aa61994-08-29 12:50:44 +00001840node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001841PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 perrdetail err;
1844 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1845 &_PyParser_Grammar,
1846 start, NULL, NULL, &err, flags);
1847 if (n == NULL)
1848 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001851}
1852
Guido van Rossuma110aa61994-08-29 12:50:44 +00001853/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001854
Guido van Rossuma110aa61994-08-29 12:50:44 +00001855node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001856PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 perrdetail err;
1859 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1860 start, &err, flags);
1861 if (n == NULL)
1862 err_input(&err);
1863 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001864}
1865
1866node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001867PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 perrdetail err;
1871 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1872 &_PyParser_Grammar, start, &err, flags);
1873 if (n == NULL)
1874 err_input(&err);
1875 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001876}
1877
1878node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001879PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001882}
1883
Guido van Rossum66ebd912003-04-17 16:02:26 +00001884/* May want to move a more generalized form of this to parsetok.c or
1885 even parser modules. */
1886
1887void
1888PyParser_SetError(perrdetail *err)
1889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001891}
1892
Guido van Rossuma110aa61994-08-29 12:50:44 +00001893/* Set the error appropriate to the given input error code (see errcode.h) */
1894
1895static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001896err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 PyObject *v, *w, *errtype, *errtext;
1899 PyObject *msg_obj = NULL;
1900 char *msg = NULL;
1901 errtype = PyExc_SyntaxError;
1902 switch (err->error) {
1903 case E_ERROR:
1904 return;
1905 case E_SYNTAX:
1906 errtype = PyExc_IndentationError;
1907 if (err->expected == INDENT)
1908 msg = "expected an indented block";
1909 else if (err->token == INDENT)
1910 msg = "unexpected indent";
1911 else if (err->token == DEDENT)
1912 msg = "unexpected unindent";
1913 else {
1914 errtype = PyExc_SyntaxError;
1915 msg = "invalid syntax";
1916 }
1917 break;
1918 case E_TOKEN:
1919 msg = "invalid token";
1920 break;
1921 case E_EOFS:
1922 msg = "EOF while scanning triple-quoted string literal";
1923 break;
1924 case E_EOLS:
1925 msg = "EOL while scanning string literal";
1926 break;
1927 case E_INTR:
1928 if (!PyErr_Occurred())
1929 PyErr_SetNone(PyExc_KeyboardInterrupt);
1930 goto cleanup;
1931 case E_NOMEM:
1932 PyErr_NoMemory();
1933 goto cleanup;
1934 case E_EOF:
1935 msg = "unexpected EOF while parsing";
1936 break;
1937 case E_TABSPACE:
1938 errtype = PyExc_TabError;
1939 msg = "inconsistent use of tabs and spaces in indentation";
1940 break;
1941 case E_OVERFLOW:
1942 msg = "expression too long";
1943 break;
1944 case E_DEDENT:
1945 errtype = PyExc_IndentationError;
1946 msg = "unindent does not match any outer indentation level";
1947 break;
1948 case E_TOODEEP:
1949 errtype = PyExc_IndentationError;
1950 msg = "too many levels of indentation";
1951 break;
1952 case E_DECODE: {
1953 PyObject *type, *value, *tb;
1954 PyErr_Fetch(&type, &value, &tb);
1955 msg = "unknown decode error";
1956 if (value != NULL)
1957 msg_obj = PyObject_Str(value);
1958 Py_XDECREF(type);
1959 Py_XDECREF(value);
1960 Py_XDECREF(tb);
1961 break;
1962 }
1963 case E_LINECONT:
1964 msg = "unexpected character after line continuation character";
1965 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 case E_IDENTIFIER:
1968 msg = "invalid character in identifier";
1969 break;
1970 default:
1971 fprintf(stderr, "error=%d\n", err->error);
1972 msg = "unknown parsing error";
1973 break;
1974 }
1975 /* err->text may not be UTF-8 in case of decoding errors.
1976 Explicitly convert to an object. */
1977 if (!err->text) {
1978 errtext = Py_None;
1979 Py_INCREF(Py_None);
1980 } else {
1981 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1982 "replace");
1983 }
1984 v = Py_BuildValue("(ziiN)", err->filename,
1985 err->lineno, err->offset, errtext);
1986 if (v != NULL) {
1987 if (msg_obj)
1988 w = Py_BuildValue("(OO)", msg_obj, v);
1989 else
1990 w = Py_BuildValue("(sO)", msg, v);
1991 } else
1992 w = NULL;
1993 Py_XDECREF(v);
1994 PyErr_SetObject(errtype, w);
1995 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001996cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 Py_XDECREF(msg_obj);
1998 if (err->text != NULL) {
1999 PyObject_FREE(err->text);
2000 err->text = NULL;
2001 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002002}
2003
2004/* Print fatal error message and abort */
2005
2006void
Tim Peters7c321a82002-07-09 02:57:01 +00002007Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 fprintf(stderr, "Fatal Python error: %s\n", msg);
2010 fflush(stderr); /* it helps in Windows debug build */
2011 if (PyErr_Occurred()) {
2012 PyErr_Print();
2013 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002014#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 {
2016 size_t len = strlen(msg);
2017 WCHAR* buffer;
2018 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 /* Convert the message to wchar_t. This uses a simple one-to-one
2021 conversion, assuming that the this error message actually uses ASCII
2022 only. If this ceases to be true, we will have to convert. */
2023 buffer = alloca( (len+1) * (sizeof *buffer));
2024 for( i=0; i<=len; ++i)
2025 buffer[i] = msg[i];
2026 OutputDebugStringW(L"Fatal Python error: ");
2027 OutputDebugStringW(buffer);
2028 OutputDebugStringW(L"\n");
2029 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002030#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002032#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002033#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002035}
2036
2037/* Clean up and exit */
2038
Guido van Rossuma110aa61994-08-29 12:50:44 +00002039#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002040#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002041#endif
2042
Collin Winter670e6922007-03-21 02:57:17 +00002043static void (*pyexitfunc)(void) = NULL;
2044/* For the atexit module. */
2045void _Py_PyAtExit(void (*func)(void))
2046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002048}
2049
2050static void
2051call_py_exitfuncs(void)
2052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (pyexitfunc == NULL)
2054 return;
Collin Winter670e6922007-03-21 02:57:17 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 (*pyexitfunc)();
2057 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002058}
2059
Antoine Pitrou011bd622009-10-20 21:52:47 +00002060/* Wait until threading._shutdown completes, provided
2061 the threading module was imported in the first place.
2062 The shutdown routine will wait until all non-daemon
2063 "threading" threads have completed. */
2064static void
2065wait_for_thread_shutdown(void)
2066{
2067#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 PyObject *result;
2069 PyThreadState *tstate = PyThreadState_GET();
2070 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2071 "threading");
2072 if (threading == NULL) {
2073 /* threading not imported */
2074 PyErr_Clear();
2075 return;
2076 }
2077 result = PyObject_CallMethod(threading, "_shutdown", "");
2078 if (result == NULL) {
2079 PyErr_WriteUnraisable(threading);
2080 }
2081 else {
2082 Py_DECREF(result);
2083 }
2084 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002085#endif
2086}
2087
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002088#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002089static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002090static int nexitfuncs = 0;
2091
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002092int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (nexitfuncs >= NEXITFUNCS)
2095 return -1;
2096 exitfuncs[nexitfuncs++] = func;
2097 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002098}
2099
Guido van Rossumcc283f51997-08-05 02:22:03 +00002100static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002101call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 while (nexitfuncs > 0)
2104 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 fflush(stdout);
2107 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002108}
2109
2110void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002111Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002116}
2117
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002118static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002119initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002120{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002121#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002123#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002124#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002126#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002127#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002129#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002131}
2132
Guido van Rossum7433b121997-02-14 19:45:36 +00002133
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002134/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2135 *
2136 * All of the code in this function must only use async-signal-safe functions,
2137 * listed at `man 7 signal` or
2138 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2139 */
2140void
2141_Py_RestoreSignals(void)
2142{
2143#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002145#endif
2146#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002148#endif
2149#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002151#endif
2152}
2153
2154
Guido van Rossum7433b121997-02-14 19:45:36 +00002155/*
2156 * The file descriptor fd is considered ``interactive'' if either
2157 * a) isatty(fd) is TRUE, or
2158 * b) the -i flag was given, and the filename associated with
2159 * the descriptor is NULL or "<stdin>" or "???".
2160 */
2161int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002162Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (isatty((int)fileno(fp)))
2165 return 1;
2166 if (!Py_InteractiveFlag)
2167 return 0;
2168 return (filename == NULL) ||
2169 (strcmp(filename, "<stdin>") == 0) ||
2170 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002171}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002172
2173
Tim Petersd08e3822003-04-17 15:24:21 +00002174#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002175#if defined(WIN32) && defined(_MSC_VER)
2176
2177/* Stack checking for Microsoft C */
2178
2179#include <malloc.h>
2180#include <excpt.h>
2181
Fred Drakee8de31c2000-08-31 05:38:39 +00002182/*
2183 * Return non-zero when we run out of memory on the stack; zero otherwise.
2184 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002185int
Fred Drake399739f2000-08-31 05:52:44 +00002186PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 __try {
2189 /* alloca throws a stack overflow exception if there's
2190 not enough space left on the stack */
2191 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2192 return 0;
2193 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2194 EXCEPTION_EXECUTE_HANDLER :
2195 EXCEPTION_CONTINUE_SEARCH) {
2196 int errcode = _resetstkoflw();
2197 if (errcode == 0)
2198 {
2199 Py_FatalError("Could not reset the stack!");
2200 }
2201 }
2202 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002203}
2204
2205#endif /* WIN32 && _MSC_VER */
2206
2207/* Alternate implementations can be added here... */
2208
2209#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002210
2211
2212/* Wrappers around sigaction() or signal(). */
2213
2214PyOS_sighandler_t
2215PyOS_getsig(int sig)
2216{
2217#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 struct sigaction context;
2219 if (sigaction(sig, NULL, &context) == -1)
2220 return SIG_ERR;
2221 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002222#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002224/* Special signal handling for the secure CRT in Visual Studio 2005 */
2225#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 switch (sig) {
2227 /* Only these signals are valid */
2228 case SIGINT:
2229 case SIGILL:
2230 case SIGFPE:
2231 case SIGSEGV:
2232 case SIGTERM:
2233 case SIGBREAK:
2234 case SIGABRT:
2235 break;
2236 /* Don't call signal() with other values or it will assert */
2237 default:
2238 return SIG_ERR;
2239 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002240#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 handler = signal(sig, SIG_IGN);
2242 if (handler != SIG_ERR)
2243 signal(sig, handler);
2244 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002245#endif
2246}
2247
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002248/*
2249 * All of the code in this function must only use async-signal-safe functions,
2250 * listed at `man 7 signal` or
2251 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2252 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002253PyOS_sighandler_t
2254PyOS_setsig(int sig, PyOS_sighandler_t handler)
2255{
2256#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 /* Some code in Modules/signalmodule.c depends on sigaction() being
2258 * used here if HAVE_SIGACTION is defined. Fix that if this code
2259 * changes to invalidate that assumption.
2260 */
2261 struct sigaction context, ocontext;
2262 context.sa_handler = handler;
2263 sigemptyset(&context.sa_mask);
2264 context.sa_flags = 0;
2265 if (sigaction(sig, &context, &ocontext) == -1)
2266 return SIG_ERR;
2267 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002268#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 PyOS_sighandler_t oldhandler;
2270 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002271#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002273#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002275#endif
2276}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277
2278/* Deprecated C API functions still provided for binary compatiblity */
2279
2280#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002281PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285}
2286
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002287#undef PyParser_SimpleParseString
2288PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002289PyParser_SimpleParseString(const char *str, int start)
2290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002293
2294#undef PyRun_AnyFile
2295PyAPI_FUNC(int)
2296PyRun_AnyFile(FILE *fp, const char *name)
2297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002299}
2300
2301#undef PyRun_AnyFileEx
2302PyAPI_FUNC(int)
2303PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002306}
2307
2308#undef PyRun_AnyFileFlags
2309PyAPI_FUNC(int)
2310PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002313}
2314
2315#undef PyRun_File
2316PyAPI_FUNC(PyObject *)
2317PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002320}
2321
2322#undef PyRun_FileEx
2323PyAPI_FUNC(PyObject *)
2324PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002327}
2328
2329#undef PyRun_FileFlags
2330PyAPI_FUNC(PyObject *)
2331PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002335}
2336
2337#undef PyRun_SimpleFile
2338PyAPI_FUNC(int)
2339PyRun_SimpleFile(FILE *f, const char *p)
2340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002342}
2343
2344#undef PyRun_SimpleFileEx
2345PyAPI_FUNC(int)
2346PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002349}
2350
2351
2352#undef PyRun_String
2353PyAPI_FUNC(PyObject *)
2354PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002357}
2358
2359#undef PyRun_SimpleString
2360PyAPI_FUNC(int)
2361PyRun_SimpleString(const char *s)
2362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002364}
2365
2366#undef Py_CompileString
2367PyAPI_FUNC(PyObject *)
2368Py_CompileString(const char *str, const char *p, int s)
2369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002371}
2372
2373#undef PyRun_InteractiveOne
2374PyAPI_FUNC(int)
2375PyRun_InteractiveOne(FILE *f, const char *p)
2376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002378}
2379
2380#undef PyRun_InteractiveLoop
2381PyAPI_FUNC(int)
2382PyRun_InteractiveLoop(FILE *f, const char *p)
2383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002385}
2386
2387#ifdef __cplusplus
2388}
2389#endif