blob: c6cf0882325ac128deaa4073f6909550dd423cc9 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Antoine Pitroucefb3162009-10-20 22:08:36 +000021#include "abstract.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000022
Thomas Wouters0e3f5912006-08-11 14:57:12 +000023#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000024#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000026
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000027#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000028#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000029#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000030
Martin v. Löwis73d538b2003-03-05 15:13:47 +000031#ifdef HAVE_LANGINFO_H
32#include <locale.h>
33#include <langinfo.h>
34#endif
35
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000036#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000037#undef BYTE
38#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000039#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000040#endif
41
Neal Norwitz4281cef2006-03-04 19:58:13 +000042#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000044#else /* Py_REF_DEBUG */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000045#define PRINT_TOTAL_REFS() fprintf(stderr, \
46 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
47 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000048#endif
49
50#ifdef __cplusplus
51extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000052#endif
53
Martin v. Löwis790465f2008-04-05 20:41:37 +000054extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000055
Guido van Rossum82598051997-03-05 00:20:32 +000056extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000057
Guido van Rossumb73cc041993-11-01 16:28:59 +000058/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000059static void initmain(void);
60static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000061static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000062static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000063static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000064 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000065static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +000066 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000067static void err_input(perrdetail *);
68static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000069static void call_py_exitfuncs(void);
Antoine Pitroucefb3162009-10-20 22:08:36 +000070static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000071static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000072extern void _PyUnicode_Init(void);
73extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000074extern int _PyLong_Init(void);
75extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000084int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000085int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000086int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000087int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000088int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000089int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000090int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000091int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000092int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000093int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000094
Christian Heimes33fe8092008-04-13 13:53:33 +000095/* PyModule_GetWarningsModule is no longer necessary as of 2.6
96since _warnings is builtin. This API should not be used. */
97PyObject *
98PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000099{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000100 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000101}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000102
Guido van Rossum25ce5661997-08-02 03:10:38 +0000103static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000104
Thomas Wouters7e474022000-07-16 12:04:32 +0000105/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106
107int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000108Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000110 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111}
112
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113/* Global initializations. Can be undone by Py_Finalize(). Don't
114 call this twice without an intervening Py_Finalize() call. When
115 initializations fail, a fatal error is issued and the function does
116 not return. On return, the first thread and interpreter state have
117 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119 Locking: you must hold the interpreter lock while calling this.
120 (If the lock has not yet been initialized, that's equivalent to
121 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000125static int
126add_flag(int flag, const char *envs)
127{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000128 int env = atoi(envs);
129 if (flag < env)
130 flag = env;
131 if (flag < 1)
132 flag = 1;
133 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000134}
135
Christian Heimes5833a2f2008-10-30 21:40:04 +0000136#if defined(HAVE_LANGINFO_H) && defined(CODESET)
137static char*
138get_codeset(void)
139{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000140 char* codeset;
141 PyObject *codec, *name;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000142
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000143 codeset = nl_langinfo(CODESET);
144 if (!codeset || codeset[0] == '\0')
145 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000146
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000147 codec = _PyCodec_Lookup(codeset);
148 if (!codec)
149 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000150
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000151 name = PyObject_GetAttrString(codec, "name");
152 Py_CLEAR(codec);
153 if (!name)
154 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000155
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000156 codeset = strdup(_PyUnicode_AsString(name));
157 Py_DECREF(name);
158 return codeset;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000159
160error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000161 Py_XDECREF(codec);
162 PyErr_Clear();
163 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000164}
165#endif
166
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000168Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000169{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000170 PyInterpreterState *interp;
171 PyThreadState *tstate;
172 PyObject *bimod, *sysmod, *pstderr;
173 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000174#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000175 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000176#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000177 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000178
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000179 if (initialized)
180 return;
181 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000182
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000183#ifdef HAVE_SETLOCALE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000184 /* Set up the LC_CTYPE locale, so we can obtain
185 the locale's charset without having to switch
186 locales. */
187 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000188#endif
189
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000190 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
191 Py_DebugFlag = add_flag(Py_DebugFlag, p);
192 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
193 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
194 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
195 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
196 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
197 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000198
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000199 interp = PyInterpreterState_New();
200 if (interp == NULL)
201 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000202
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000203 tstate = PyThreadState_New(interp);
204 if (tstate == NULL)
205 Py_FatalError("Py_Initialize: can't make first thread");
206 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000207
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000208 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000209
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000210 if (!_PyFrame_Init())
211 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000212
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000213 if (!_PyLong_Init())
214 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000215
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000216 if (!PyByteArray_Init())
217 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000218
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000219 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000220
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000221 interp->modules = PyDict_New();
222 if (interp->modules == NULL)
223 Py_FatalError("Py_Initialize: can't make modules dictionary");
224 interp->modules_reloading = PyDict_New();
225 if (interp->modules_reloading == NULL)
226 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000227
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000228 /* Init Unicode implementation; relies on the codec registry */
229 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000230
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000231 bimod = _PyBuiltin_Init();
232 if (bimod == NULL)
233 Py_FatalError("Py_Initialize: can't initialize builtins modules");
234 _PyImport_FixupExtension(bimod, "builtins", "builtins");
235 interp->builtins = PyModule_GetDict(bimod);
236 if (interp->builtins == NULL)
237 Py_FatalError("Py_Initialize: can't initialize builtins dict");
238 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000239
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000240 /* initialize builtin exceptions */
241 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000242
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000243 sysmod = _PySys_Init();
244 if (sysmod == NULL)
245 Py_FatalError("Py_Initialize: can't initialize sys");
246 interp->sysdict = PyModule_GetDict(sysmod);
247 if (interp->sysdict == NULL)
248 Py_FatalError("Py_Initialize: can't initialize sys dict");
249 Py_INCREF(interp->sysdict);
250 _PyImport_FixupExtension(sysmod, "sys", "sys");
251 PySys_SetPath(Py_GetPath());
252 PyDict_SetItemString(interp->sysdict, "modules",
253 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000254
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000255 /* Set up a preliminary stderr printer until we have enough
256 infrastructure for the io module in place. */
257 pstderr = PyFile_NewStdPrinter(fileno(stderr));
258 if (pstderr == NULL)
259 Py_FatalError("Py_Initialize: can't set preliminary stderr");
260 PySys_SetObject("stderr", pstderr);
261 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamoto3d897512010-10-30 15:43:30 +0000262 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000263
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000264 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000265
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000266 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000267
Victor Stinner148051a2010-05-20 21:00:34 +0000268 /* Initialize _warnings. */
269 _PyWarnings_Init();
270
Martin v. Löwis011e8422009-05-05 04:43:17 +0000271#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000272 /* On Unix, set the file system encoding according to the
273 user's preference, if the CODESET names a well-known
274 Python codec, and Py_FileSystemDefaultEncoding isn't
275 initialized by other means. Also set the encoding of
276 stdin and stdout if these are terminals. */
Martin v. Löwis011e8422009-05-05 04:43:17 +0000277
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000278 codeset = get_codeset();
279 if (codeset) {
280 if (!Py_FileSystemDefaultEncoding)
281 Py_FileSystemDefaultEncoding = codeset;
282 else
283 free(codeset);
284 }
Martin v. Löwis011e8422009-05-05 04:43:17 +0000285#endif
286
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000287 if (install_sigs)
288 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000289
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000290 /* Initialize warnings. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000291 if (PySys_HasWarnOptions()) {
292 PyObject *warnings_module = PyImport_ImportModule("warnings");
293 if (!warnings_module)
294 PyErr_Clear();
295 Py_XDECREF(warnings_module);
296 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000297
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000298 initmain(); /* Module __main__ */
299 if (initstdio() < 0)
300 Py_FatalError(
301 "Py_Initialize: can't initialize sys standard streams");
302
303 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000304#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000305 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000306#endif /* WITH_THREAD */
Victor Stinnerffbc2f62010-03-21 21:48:45 +0000307
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000308 if (!Py_NoSiteFlag)
309 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310}
311
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000312void
313Py_Initialize(void)
314{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000315 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000316}
317
318
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000319#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000320extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000321#endif
322
Guido van Rossume8432ac2007-07-09 15:04:50 +0000323/* Flush stdout and stderr */
324
Neal Norwitz2bad9702007-08-27 06:19:22 +0000325static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000326flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000327{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000328 PyObject *fout = PySys_GetObject("stdout");
329 PyObject *ferr = PySys_GetObject("stderr");
330 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000331
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000332 if (fout != NULL && fout != Py_None) {
333 tmp = PyObject_CallMethod(fout, "flush", "");
334 if (tmp == NULL)
Antoine Pitroub61d5c92010-08-08 20:49:19 +0000335 PyErr_WriteUnraisable(fout);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000336 else
337 Py_DECREF(tmp);
338 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000339
Victor Stinnerebb5a882010-05-14 01:03:14 +0000340 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000341 tmp = PyObject_CallMethod(ferr, "flush", "");
342 if (tmp == NULL)
343 PyErr_Clear();
344 else
345 Py_DECREF(tmp);
346 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000347}
348
Guido van Rossum25ce5661997-08-02 03:10:38 +0000349/* Undo the effect of Py_Initialize().
350
351 Beware: if multiple interpreter and/or thread states exist, these
352 are not wiped out; only the current thread and interpreter state
353 are deleted. But since everything else is deleted, those other
354 interpreter and thread states should no longer be used.
355
356 (XXX We should do better, e.g. wipe out all interpreters and
357 threads.)
358
359 Locking: as above.
360
361*/
362
363void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000364Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000365{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000366 PyInterpreterState *interp;
367 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000369 if (!initialized)
370 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000371
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000372 wait_for_thread_shutdown();
Antoine Pitroucefb3162009-10-20 22:08:36 +0000373
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000374 /* The interpreter is still entirely intact at this point, and the
375 * exit funcs may be relying on that. In particular, if some thread
376 * or exit func is still waiting to do an import, the import machinery
377 * expects Py_IsInitialized() to return true. So don't say the
378 * interpreter is uninitialized until after the exit funcs have run.
379 * Note that Threading.py uses an exit func to do a join on all the
380 * threads created thru it, so this also protects pending imports in
381 * the threads created via Threading.
382 */
383 call_py_exitfuncs();
384 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000385
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000386 /* Flush stdout+stderr */
387 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000388
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000389 /* Get current thread state and interpreter pointer */
390 tstate = PyThreadState_GET();
391 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000392
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000393 /* Disable signal handling */
394 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000395
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000396 /* Clear type lookup cache */
397 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000398
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000399 /* Collect garbage. This may call finalizers; it's nice to call these
400 * before all modules are destroyed.
401 * XXX If a __del__ or weakref callback is triggered here, and tries to
402 * XXX import a module, bad things can happen, because Python no
403 * XXX longer believes it's initialized.
404 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
405 * XXX is easy to provoke that way. I've also seen, e.g.,
406 * XXX Exception exceptions.ImportError: 'No module named sha'
407 * XXX in <function callback at 0x008F5718> ignored
408 * XXX but I'm unclear on exactly how that one happens. In any case,
409 * XXX I haven't seen a real-life report of either of these.
410 */
411 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000412#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000413 /* With COUNT_ALLOCS, it helps to run GC multiple times:
414 each collection might release some types from the type
415 list, so they become garbage. */
416 while (PyGC_Collect() > 0)
417 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000418#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000419
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000420 /* Destroy all modules */
421 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000422
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000423 /* Flush stdout+stderr (again, in case more was printed) */
424 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000425
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000426 /* Collect final garbage. This disposes of cycles created by
427 * new-style class definitions, for example.
428 * XXX This is disabled because it caused too many problems. If
429 * XXX a __del__ or weakref callback triggers here, Python code has
430 * XXX a hard time running, because even the sys module has been
431 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
432 * XXX One symptom is a sequence of information-free messages
433 * XXX coming from threads (if a __del__ or callback is invoked,
434 * XXX other threads can execute too, and any exception they encounter
435 * XXX triggers a comedy of errors as subsystem after subsystem
436 * XXX fails to find what it *expects* to find in sys to help report
437 * XXX the exception and consequent unexpected failures). I've also
438 * XXX seen segfaults then, after adding print statements to the
439 * XXX Python code getting called.
440 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000441#if 0
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000442 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000443#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000444
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000445 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
446 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000447
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000448 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000449#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000450 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000451#endif
452
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000453 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000454
Tim Peters9cf25ce2003-04-17 15:21:01 +0000455#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000456 /* Display all objects still alive -- this can invoke arbitrary
457 * __repr__ overrides, so requires a mostly-intact interpreter.
458 * Alas, a lot of stuff may still be alive now that will be cleaned
459 * up later.
460 */
461 if (Py_GETENV("PYTHONDUMPREFS"))
462 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000463#endif /* Py_TRACE_REFS */
464
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000465 /* Clear interpreter state */
466 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000467
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000468 /* Now we decref the exception classes. After this point nothing
469 can raise an exception. That's okay, because each Fini() method
470 below has been checked to make sure no exceptions are ever
471 raised.
472 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000473
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000474 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000475
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000476 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000477#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000478 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000479#endif /* WITH_THREAD */
480
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000481 /* Delete current thread */
482 PyThreadState_Swap(NULL);
483 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000484
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000485 /* Sundry finalizers */
486 PyMethod_Fini();
487 PyFrame_Fini();
488 PyCFunction_Fini();
489 PyTuple_Fini();
490 PyList_Fini();
491 PySet_Fini();
492 PyBytes_Fini();
493 PyByteArray_Fini();
494 PyLong_Fini();
495 PyFloat_Fini();
496 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000497
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000498 /* Cleanup Unicode implementation */
499 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000500
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000501 /* reset file system default encoding */
502 if (!Py_HasFileSystemDefaultEncoding) {
503 free((char*)Py_FileSystemDefaultEncoding);
504 Py_FileSystemDefaultEncoding = NULL;
505 }
Christian Heimesc8967002007-11-30 10:18:26 +0000506
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000507 /* XXX Still allocated:
508 - various static ad-hoc pointers to interned strings
509 - int and float free list blocks
510 - whatever various modules and libraries allocate
511 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000512
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000513 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000514
Tim Peters269b2a62003-04-17 19:52:29 +0000515#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000516 /* Display addresses (& refcnts) of all objects still alive.
517 * An address can be used to find the repr of the object, printed
518 * above by _Py_PrintReferences.
519 */
520 if (Py_GETENV("PYTHONDUMPREFS"))
521 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000522#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000523#ifdef PYMALLOC_DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000524 if (Py_GETENV("PYTHONMALLOCSTATS"))
525 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000526#endif
527
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000528 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000529}
530
531/* Create and initialize a new interpreter and thread, and return the
532 new thread. This requires that Py_Initialize() has been called
533 first.
534
535 Unsuccessful initialization yields a NULL pointer. Note that *no*
536 exception information is available even in this case -- the
537 exception information is held in the thread, and there is no
538 thread.
539
540 Locking: as above.
541
542*/
543
544PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000545Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000546{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000547 PyInterpreterState *interp;
548 PyThreadState *tstate, *save_tstate;
549 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000550
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000551 if (!initialized)
552 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000553
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000554 interp = PyInterpreterState_New();
555 if (interp == NULL)
556 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000557
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000558 tstate = PyThreadState_New(interp);
559 if (tstate == NULL) {
560 PyInterpreterState_Delete(interp);
561 return NULL;
562 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000563
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000564 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000566 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000568 interp->modules = PyDict_New();
569 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000571 bimod = _PyImport_FindExtension("builtins", "builtins");
572 if (bimod != NULL) {
573 interp->builtins = PyModule_GetDict(bimod);
574 if (interp->builtins == NULL)
575 goto handle_error;
576 Py_INCREF(interp->builtins);
577 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000578
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000579 /* initialize builtin exceptions */
580 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000581
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000582 sysmod = _PyImport_FindExtension("sys", "sys");
583 if (bimod != NULL && sysmod != NULL) {
584 PyObject *pstderr;
585 interp->sysdict = PyModule_GetDict(sysmod);
586 if (interp->sysdict == NULL)
587 goto handle_error;
588 Py_INCREF(interp->sysdict);
589 PySys_SetPath(Py_GetPath());
590 PyDict_SetItemString(interp->sysdict, "modules",
591 interp->modules);
592 /* Set up a preliminary stderr printer until we have enough
593 infrastructure for the io module in place. */
594 pstderr = PyFile_NewStdPrinter(fileno(stderr));
595 if (pstderr == NULL)
596 Py_FatalError("Py_Initialize: can't set preliminary stderr");
597 PySys_SetObject("stderr", pstderr);
598 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamoto3d897512010-10-30 15:43:30 +0000599 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000600
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000601 _PyImportHooks_Init();
602 if (initstdio() < 0)
603 Py_FatalError(
604 "Py_Initialize: can't initialize sys standard streams");
605 initmain();
606 if (!Py_NoSiteFlag)
607 initsite();
608 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000609
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000610 if (!PyErr_Occurred())
611 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000612
Thomas Wouters89f507f2006-12-13 04:49:30 +0000613handle_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000614 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000615
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000616 PyErr_Print();
617 PyThreadState_Clear(tstate);
618 PyThreadState_Swap(save_tstate);
619 PyThreadState_Delete(tstate);
620 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000622 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623}
624
625/* Delete an interpreter and its last thread. This requires that the
626 given thread state is current, that the thread has no remaining
627 frames, and that it is its interpreter's only remaining thread.
628 It is a fatal error to violate these constraints.
629
630 (Py_Finalize() doesn't have these constraints -- it zaps
631 everything, regardless.)
632
633 Locking: as above.
634
635*/
636
637void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000638Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000639{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000640 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000641
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000642 if (tstate != PyThreadState_GET())
643 Py_FatalError("Py_EndInterpreter: thread is not current");
644 if (tstate->frame != NULL)
645 Py_FatalError("Py_EndInterpreter: thread still has a frame");
646 if (tstate != interp->tstate_head || tstate->next != NULL)
647 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000648
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000649 PyImport_Cleanup();
650 PyInterpreterState_Clear(interp);
651 PyThreadState_Swap(NULL);
652 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000653}
654
Martin v. Löwis790465f2008-04-05 20:41:37 +0000655static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000656
657void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000658Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000659{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000660 if (pn && *pn)
661 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000662}
663
Martin v. Löwis790465f2008-04-05 20:41:37 +0000664wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000665Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000666{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000667 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000668}
669
Martin v. Löwis790465f2008-04-05 20:41:37 +0000670static wchar_t *default_home = NULL;
671static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000672
673void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000674Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000675{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000676 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000677}
678
Martin v. Löwis790465f2008-04-05 20:41:37 +0000679wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000680Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000681{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000682 wchar_t *home = default_home;
683 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
684 char* chome = Py_GETENV("PYTHONHOME");
685 if (chome) {
686 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
687 if (r != (size_t)-1 && r <= PATH_MAX)
688 home = env_home;
689 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000690
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000691 }
692 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000693}
694
Guido van Rossum6135a871995-01-09 17:53:26 +0000695/* Create __main__ module */
696
697static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000698initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000699{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000700 PyObject *m, *d;
701 m = PyImport_AddModule("__main__");
702 if (m == NULL)
703 Py_FatalError("can't create __main__ module");
704 d = PyModule_GetDict(m);
705 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
706 PyObject *bimod = PyImport_ImportModule("builtins");
707 if (bimod == NULL ||
708 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
709 Py_FatalError("can't add __builtins__ to __main__");
710 Py_DECREF(bimod);
711 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000712}
713
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000714/* Import the site module (not into __main__ though) */
715
716static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000717initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000718{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000719 PyObject *m, *f;
720 m = PyImport_ImportModule("site");
721 if (m == NULL) {
722 f = PySys_GetObject("stderr");
723 if (f == NULL || f == Py_None)
724 return;
725 if (Py_VerboseFlag) {
Victor Stinner3aa6cea2010-10-23 08:50:36 +0000726 PyObject *type, *value, *traceback;
727 PyErr_Fetch(&type, &value, &traceback);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000728 PyFile_WriteString(
729 "'import site' failed; traceback:\n", f);
Victor Stinner3aa6cea2010-10-23 08:50:36 +0000730 PyErr_Restore(type, value, traceback);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000731 PyErr_Print();
732 }
733 else {
Victor Stinner3aa6cea2010-10-23 08:50:36 +0000734 PyErr_Clear();
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000735 PyFile_WriteString(
736 "'import site' failed; use -v for traceback\n", f);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000737 }
738 }
739 else {
740 Py_DECREF(m);
741 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000742}
743
Antoine Pitrou05608432009-01-09 18:53:14 +0000744static PyObject*
745create_stdio(PyObject* io,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000746 int fd, int write_mode, char* name,
747 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000748{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000749 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
750 const char* mode;
751 PyObject *line_buffering;
752 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000753
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000754 /* stdin is always opened in buffered mode, first because it shouldn't
755 make a difference in common use cases, second because TextIOWrapper
756 depends on the presence of a read1() method which only exists on
757 buffered streams.
758 */
759 if (Py_UnbufferedStdioFlag && write_mode)
760 buffering = 0;
761 else
762 buffering = -1;
763 if (write_mode)
764 mode = "wb";
765 else
766 mode = "rb";
767 buf = PyObject_CallMethod(io, "open", "isiOOOi",
768 fd, mode, buffering,
769 Py_None, Py_None, Py_None, 0);
770 if (buf == NULL)
771 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000772
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000773 if (buffering) {
774 raw = PyObject_GetAttrString(buf, "raw");
775 if (raw == NULL)
776 goto error;
777 }
778 else {
779 raw = buf;
780 Py_INCREF(raw);
781 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000782
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000783 text = PyUnicode_FromString(name);
784 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
785 goto error;
786 res = PyObject_CallMethod(raw, "isatty", "");
787 if (res == NULL)
788 goto error;
789 isatty = PyObject_IsTrue(res);
790 Py_DECREF(res);
791 if (isatty == -1)
792 goto error;
793 if (isatty || Py_UnbufferedStdioFlag)
794 line_buffering = Py_True;
795 else
796 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000797
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000798 Py_CLEAR(raw);
799 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000800
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000801 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
802 buf, encoding, errors,
803 "\n", line_buffering);
804 Py_CLEAR(buf);
805 if (stream == NULL)
806 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000807
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000808 if (write_mode)
809 mode = "w";
810 else
811 mode = "r";
812 text = PyUnicode_FromString(mode);
813 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
814 goto error;
815 Py_CLEAR(text);
816 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000817
818error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000819 Py_XDECREF(buf);
820 Py_XDECREF(stream);
821 Py_XDECREF(text);
822 Py_XDECREF(raw);
823 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000824}
825
Georg Brandl1a3284e2007-12-02 09:40:06 +0000826/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000827static int
828initstdio(void)
829{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000830 PyObject *iomod = NULL, *wrapper;
831 PyObject *bimod = NULL;
832 PyObject *m;
833 PyObject *std = NULL;
834 int status = 0, fd;
835 PyObject * encoding_attr;
836 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000837
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000838 /* Hack to avoid a nasty recursion issue when Python is invoked
839 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
840 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
841 goto error;
842 }
843 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000844
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000845 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
846 goto error;
847 }
848 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000849
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000850 if (!(bimod = PyImport_ImportModule("builtins"))) {
851 goto error;
852 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000853
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000854 if (!(iomod = PyImport_ImportModule("io"))) {
855 goto error;
856 }
857 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
858 goto error;
859 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000860
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000861 /* Set builtins.open */
862 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
863 goto error;
864 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000865
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000866 encoding = Py_GETENV("PYTHONIOENCODING");
867 errors = NULL;
868 if (encoding) {
869 encoding = strdup(encoding);
870 errors = strchr(encoding, ':');
871 if (errors) {
872 *errors = '\0';
873 errors++;
874 }
875 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000876
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000877 /* Set sys.stdin */
878 fd = fileno(stdin);
879 /* Under some conditions stdin, stdout and stderr may not be connected
880 * and fileno() may point to an invalid file descriptor. For example
881 * GUI apps don't have valid standard streams by default.
882 */
883 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000884#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000885 std = Py_None;
886 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000887#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000888 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000889#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000890 }
891 else {
892 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
893 if (std == NULL)
894 goto error;
895 } /* if (fd < 0) */
896 PySys_SetObject("__stdin__", std);
897 PySys_SetObject("stdin", std);
898 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000899
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000900 /* Set sys.stdout */
901 fd = fileno(stdout);
902 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000903#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000904 std = Py_None;
905 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000906#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000907 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000908#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000909 }
910 else {
911 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
912 if (std == NULL)
913 goto error;
914 } /* if (fd < 0) */
915 PySys_SetObject("__stdout__", std);
916 PySys_SetObject("stdout", std);
917 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000918
Guido van Rossum98297ee2007-11-06 21:34:58 +0000919#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000920 /* Set sys.stderr, replaces the preliminary stderr */
921 fd = fileno(stderr);
922 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000923#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000924 std = Py_None;
925 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000926#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000927 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000928#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000929 }
930 else {
931 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
932 if (std == NULL)
933 goto error;
934 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000935
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000936 /* Same as hack above, pre-import stderr's codec to avoid recursion
937 when import.c tries to write to stderr in verbose mode. */
938 encoding_attr = PyObject_GetAttrString(std, "encoding");
939 if (encoding_attr != NULL) {
940 const char * encoding;
941 encoding = _PyUnicode_AsString(encoding_attr);
942 if (encoding != NULL) {
943 _PyCodec_Lookup(encoding);
944 }
Hirokazu Yamamoto3d897512010-10-30 15:43:30 +0000945 Py_DECREF(encoding_attr);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000946 }
947 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000948
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000949 PySys_SetObject("__stderr__", std);
950 PySys_SetObject("stderr", std);
951 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000952#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000953
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000954 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000955 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000956 status = -1;
957 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000958
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000959 if (encoding)
960 free(encoding);
961 Py_XDECREF(bimod);
962 Py_XDECREF(iomod);
963 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000964}
965
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000966/* Parse input from a file and execute it */
967
968int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000969PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000970 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000971{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000972 if (filename == NULL)
973 filename = "???";
974 if (Py_FdIsInteractive(fp, filename)) {
975 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
976 if (closeit)
977 fclose(fp);
978 return err;
979 }
980 else
981 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000982}
983
984int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000985PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000986{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000987 PyObject *v;
988 int ret;
989 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000990
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000991 if (flags == NULL) {
992 flags = &local_flags;
993 local_flags.cf_flags = 0;
994 }
995 v = PySys_GetObject("ps1");
996 if (v == NULL) {
997 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
998 Py_XDECREF(v);
999 }
1000 v = PySys_GetObject("ps2");
1001 if (v == NULL) {
1002 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1003 Py_XDECREF(v);
1004 }
1005 for (;;) {
1006 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1007 PRINT_TOTAL_REFS();
1008 if (ret == E_EOF)
1009 return 0;
1010 /*
1011 if (ret == E_NOMEM)
1012 return -1;
1013 */
1014 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001015}
1016
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001017/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001018static int PARSER_FLAGS(PyCompilerFlags *flags)
1019{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001020 int parser_flags = 0;
1021 if (!flags)
1022 return 0;
1023 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1024 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1025 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1026 parser_flags |= PyPARSE_IGNORE_COOKIE;
1027 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1028 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1029 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001030}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001031
Thomas Wouters89f507f2006-12-13 04:49:30 +00001032#if 0
1033/* Keep an example of flags with future keyword support. */
1034#define PARSER_FLAGS(flags) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001035 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1036 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1037 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1038 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001039#endif
1040
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001041int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001042PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001043{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001044 PyObject *m, *d, *v, *w, *oenc = NULL;
1045 mod_ty mod;
1046 PyArena *arena;
1047 char *ps1 = "", *ps2 = "", *enc = NULL;
1048 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001049
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001050 if (fp == stdin) {
1051 /* Fetch encoding from sys.stdin */
1052 v = PySys_GetObject("stdin");
1053 if (v == NULL || v == Py_None)
1054 return -1;
1055 oenc = PyObject_GetAttrString(v, "encoding");
1056 if (!oenc)
1057 return -1;
1058 enc = _PyUnicode_AsString(oenc);
1059 }
1060 v = PySys_GetObject("ps1");
1061 if (v != NULL) {
1062 v = PyObject_Str(v);
1063 if (v == NULL)
1064 PyErr_Clear();
1065 else if (PyUnicode_Check(v))
1066 ps1 = _PyUnicode_AsString(v);
1067 }
1068 w = PySys_GetObject("ps2");
1069 if (w != NULL) {
1070 w = PyObject_Str(w);
1071 if (w == NULL)
1072 PyErr_Clear();
1073 else if (PyUnicode_Check(w))
1074 ps2 = _PyUnicode_AsString(w);
1075 }
1076 arena = PyArena_New();
1077 if (arena == NULL) {
1078 Py_XDECREF(v);
1079 Py_XDECREF(w);
1080 Py_XDECREF(oenc);
1081 return -1;
1082 }
1083 mod = PyParser_ASTFromFile(fp, filename, enc,
1084 Py_single_input, ps1, ps2,
1085 flags, &errcode, arena);
1086 Py_XDECREF(v);
1087 Py_XDECREF(w);
1088 Py_XDECREF(oenc);
1089 if (mod == NULL) {
1090 PyArena_Free(arena);
1091 if (errcode == E_EOF) {
1092 PyErr_Clear();
1093 return E_EOF;
1094 }
1095 PyErr_Print();
1096 return -1;
1097 }
1098 m = PyImport_AddModule("__main__");
1099 if (m == NULL) {
1100 PyArena_Free(arena);
1101 return -1;
1102 }
1103 d = PyModule_GetDict(m);
1104 v = run_mod(mod, filename, d, d, flags, arena);
1105 PyArena_Free(arena);
1106 flush_io();
1107 if (v == NULL) {
1108 PyErr_Print();
1109 return -1;
1110 }
1111 Py_DECREF(v);
1112 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001113}
1114
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001115/* Check whether a file maybe a pyc file: Look at the extension,
1116 the file type, and, if we may close it, at the first few bytes. */
1117
1118static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001119maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001120{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001121 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1122 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001123
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001124 /* Only look into the file if we are allowed to close it, since
1125 it then should also be seekable. */
1126 if (closeit) {
1127 /* Read only two bytes of the magic. If the file was opened in
1128 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1129 be read as they are on disk. */
1130 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1131 unsigned char buf[2];
1132 /* Mess: In case of -x, the stream is NOT at its start now,
1133 and ungetc() was used to push back the first newline,
1134 which makes the current stream position formally undefined,
1135 and a x-platform nightmare.
1136 Unfortunately, we have no direct way to know whether -x
1137 was specified. So we use a terrible hack: if the current
1138 stream position is not 0, we assume -x was specified, and
1139 give up. Bug 132850 on SourceForge spells out the
1140 hopelessness of trying anything else (fseek and ftell
1141 don't work predictably x-platform for text-mode files).
1142 */
1143 int ispyc = 0;
1144 if (ftell(fp) == 0) {
1145 if (fread(buf, 1, 2, fp) == 2 &&
1146 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1147 ispyc = 1;
1148 rewind(fp);
1149 }
1150 return ispyc;
1151 }
1152 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001153}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001154
Guido van Rossum0df002c2000-08-27 19:21:52 +00001155int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001156PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001157 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001158{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001159 PyObject *m, *d, *v;
1160 const char *ext;
1161 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001162
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001163 m = PyImport_AddModule("__main__");
1164 if (m == NULL)
1165 return -1;
1166 d = PyModule_GetDict(m);
1167 if (PyDict_GetItemString(d, "__file__") == NULL) {
1168 PyObject *f;
Victor Stinner15244f72010-10-19 01:22:07 +00001169 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001170 if (f == NULL)
1171 return -1;
1172 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1173 Py_DECREF(f);
1174 return -1;
1175 }
1176 set_file_name = 1;
1177 Py_DECREF(f);
1178 }
1179 len = strlen(filename);
1180 ext = filename + len - (len > 4 ? 4 : 0);
1181 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1182 /* Try to run a pyc file. First, re-open in binary */
1183 if (closeit)
1184 fclose(fp);
1185 if ((fp = fopen(filename, "rb")) == NULL) {
1186 fprintf(stderr, "python: Can't reopen .pyc file\n");
1187 ret = -1;
1188 goto done;
1189 }
1190 /* Turn on optimization if a .pyo file is given */
1191 if (strcmp(ext, ".pyo") == 0)
1192 Py_OptimizeFlag = 1;
1193 v = run_pyc_file(fp, filename, d, d, flags);
1194 } else {
1195 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1196 closeit, flags);
1197 }
1198 flush_io();
1199 if (v == NULL) {
1200 PyErr_Print();
1201 ret = -1;
1202 goto done;
1203 }
1204 Py_DECREF(v);
1205 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001206 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001207 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1208 PyErr_Clear();
1209 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001210}
1211
1212int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001213PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001214{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001215 PyObject *m, *d, *v;
1216 m = PyImport_AddModule("__main__");
1217 if (m == NULL)
1218 return -1;
1219 d = PyModule_GetDict(m);
1220 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1221 if (v == NULL) {
1222 PyErr_Print();
1223 return -1;
1224 }
1225 Py_DECREF(v);
1226 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001227}
1228
Barry Warsaw035574d1997-08-29 22:07:17 +00001229static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001230parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001231 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001232{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001233 long hold;
1234 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001235
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001236 /* old style errors */
1237 if (PyTuple_Check(err))
1238 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1239 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001240
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001241 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001242
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001243 if (! (v = PyObject_GetAttrString(err, "msg")))
1244 goto finally;
1245 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001246
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001247 if (!(v = PyObject_GetAttrString(err, "filename")))
1248 goto finally;
1249 if (v == Py_None)
1250 *filename = NULL;
1251 else if (! (*filename = _PyUnicode_AsString(v)))
1252 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001253
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001254 Py_DECREF(v);
1255 if (!(v = PyObject_GetAttrString(err, "lineno")))
1256 goto finally;
1257 hold = PyLong_AsLong(v);
1258 Py_DECREF(v);
1259 v = NULL;
1260 if (hold < 0 && PyErr_Occurred())
1261 goto finally;
1262 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001263
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001264 if (!(v = PyObject_GetAttrString(err, "offset")))
1265 goto finally;
1266 if (v == Py_None) {
1267 *offset = -1;
1268 Py_DECREF(v);
1269 v = NULL;
1270 } else {
1271 hold = PyLong_AsLong(v);
1272 Py_DECREF(v);
1273 v = NULL;
1274 if (hold < 0 && PyErr_Occurred())
1275 goto finally;
1276 *offset = (int)hold;
1277 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001278
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001279 if (!(v = PyObject_GetAttrString(err, "text")))
1280 goto finally;
1281 if (v == Py_None)
1282 *text = NULL;
1283 else if (!PyUnicode_Check(v) ||
1284 !(*text = _PyUnicode_AsString(v)))
1285 goto finally;
1286 Py_DECREF(v);
1287 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001288
1289finally:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001290 Py_XDECREF(v);
1291 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001292}
1293
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001294void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001295PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001296{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001297 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001298}
1299
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001300static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001301print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001302{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001303 char *nl;
1304 if (offset >= 0) {
Benjamin Petersonc8850d02010-10-29 04:02:30 +00001305 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1306 offset--;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001307 for (;;) {
1308 nl = strchr(text, '\n');
1309 if (nl == NULL || nl-text >= offset)
1310 break;
1311 offset -= (int)(nl+1-text);
1312 text = nl+1;
1313 }
1314 while (*text == ' ' || *text == '\t') {
1315 text++;
1316 offset--;
1317 }
1318 }
1319 PyFile_WriteString(" ", f);
1320 PyFile_WriteString(text, f);
1321 if (*text == '\0' || text[strlen(text)-1] != '\n')
1322 PyFile_WriteString("\n", f);
1323 if (offset == -1)
1324 return;
1325 PyFile_WriteString(" ", f);
Benjamin Petersonc8850d02010-10-29 04:02:30 +00001326 while (--offset > 0)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001327 PyFile_WriteString(" ", f);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001328 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001329}
1330
Guido van Rossum66e8e862001-03-23 17:54:43 +00001331static void
1332handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001333{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001334 PyObject *exception, *value, *tb;
1335 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001336
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001337 if (Py_InspectFlag)
1338 /* Don't exit if -i flag was given. This flag is set to 0
1339 * when entering interactive mode for inspecting. */
1340 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001341
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001342 PyErr_Fetch(&exception, &value, &tb);
1343 fflush(stdout);
1344 if (value == NULL || value == Py_None)
1345 goto done;
1346 if (PyExceptionInstance_Check(value)) {
1347 /* The error code should be in the `code' attribute. */
1348 PyObject *code = PyObject_GetAttrString(value, "code");
1349 if (code) {
1350 Py_DECREF(value);
1351 value = code;
1352 if (value == Py_None)
1353 goto done;
1354 }
1355 /* If we failed to dig out the 'code' attribute,
1356 just let the else clause below print the error. */
1357 }
1358 if (PyLong_Check(value))
1359 exitcode = (int)PyLong_AsLong(value);
1360 else {
Victor Stinner2e71d012010-05-17 09:35:44 +00001361 PyObject *sys_stderr = PySys_GetObject("stderr");
1362 if (sys_stderr != NULL)
1363 PyObject_CallMethod(sys_stderr, "flush", NULL);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001364 PyObject_Print(value, stderr, Py_PRINT_RAW);
Victor Stinner2e71d012010-05-17 09:35:44 +00001365 fflush(stderr);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001366 PySys_WriteStderr("\n");
1367 exitcode = 1;
1368 }
Tim Peterscf615b52003-04-19 18:47:02 +00001369 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001370 /* Restore and clear the exception info, in order to properly decref
1371 * the exception, value, and traceback. If we just exit instead,
1372 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1373 * some finalizers from running.
1374 */
1375 PyErr_Restore(exception, value, tb);
1376 PyErr_Clear();
1377 Py_Exit(exitcode);
1378 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001379}
1380
1381void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001382PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001383{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001384 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001385
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001386 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1387 handle_system_exit();
1388 }
1389 PyErr_Fetch(&exception, &v, &tb);
1390 if (exception == NULL)
1391 return;
1392 PyErr_NormalizeException(&exception, &v, &tb);
1393 if (tb == NULL) {
1394 tb = Py_None;
1395 Py_INCREF(tb);
1396 }
1397 PyException_SetTraceback(v, tb);
1398 if (exception == NULL)
1399 return;
1400 /* Now we know v != NULL too */
1401 if (set_sys_last_vars) {
1402 PySys_SetObject("last_type", exception);
1403 PySys_SetObject("last_value", v);
1404 PySys_SetObject("last_traceback", tb);
1405 }
1406 hook = PySys_GetObject("excepthook");
1407 if (hook) {
1408 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1409 PyObject *result = PyEval_CallObject(hook, args);
1410 if (result == NULL) {
1411 PyObject *exception2, *v2, *tb2;
1412 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1413 handle_system_exit();
1414 }
1415 PyErr_Fetch(&exception2, &v2, &tb2);
1416 PyErr_NormalizeException(&exception2, &v2, &tb2);
1417 /* It should not be possible for exception2 or v2
1418 to be NULL. However PyErr_Display() can't
1419 tolerate NULLs, so just be safe. */
1420 if (exception2 == NULL) {
1421 exception2 = Py_None;
1422 Py_INCREF(exception2);
1423 }
1424 if (v2 == NULL) {
1425 v2 = Py_None;
1426 Py_INCREF(v2);
1427 }
1428 fflush(stdout);
1429 PySys_WriteStderr("Error in sys.excepthook:\n");
1430 PyErr_Display(exception2, v2, tb2);
1431 PySys_WriteStderr("\nOriginal exception was:\n");
1432 PyErr_Display(exception, v, tb);
1433 Py_DECREF(exception2);
1434 Py_DECREF(v2);
1435 Py_XDECREF(tb2);
1436 }
1437 Py_XDECREF(result);
1438 Py_XDECREF(args);
1439 } else {
1440 PySys_WriteStderr("sys.excepthook is missing\n");
1441 PyErr_Display(exception, v, tb);
1442 }
1443 Py_XDECREF(exception);
1444 Py_XDECREF(v);
1445 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001446}
1447
Benjamin Petersone6528212008-07-15 15:32:09 +00001448static void
1449print_exception(PyObject *f, PyObject *value)
1450{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001451 int err = 0;
1452 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001453
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001454 if (!PyExceptionInstance_Check(value)) {
1455 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1456 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1457 PyFile_WriteString(" found\n", f);
1458 return;
1459 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001460
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001461 Py_INCREF(value);
1462 fflush(stdout);
1463 type = (PyObject *) Py_TYPE(value);
1464 tb = PyException_GetTraceback(value);
1465 if (tb && tb != Py_None)
1466 err = PyTraceBack_Print(tb, f);
1467 if (err == 0 &&
1468 PyObject_HasAttrString(value, "print_file_and_line"))
1469 {
1470 PyObject *message;
1471 const char *filename, *text;
1472 int lineno, offset;
1473 if (!parse_syntax_error(value, &message, &filename,
1474 &lineno, &offset, &text))
1475 PyErr_Clear();
1476 else {
1477 char buf[10];
1478 PyFile_WriteString(" File \"", f);
1479 if (filename == NULL)
1480 PyFile_WriteString("<string>", f);
1481 else
1482 PyFile_WriteString(filename, f);
1483 PyFile_WriteString("\", line ", f);
1484 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1485 PyFile_WriteString(buf, f);
1486 PyFile_WriteString("\n", f);
1487 if (text != NULL)
1488 print_error_text(f, offset, text);
1489 Py_DECREF(value);
1490 value = message;
1491 /* Can't be bothered to check all those
1492 PyFile_WriteString() calls */
1493 if (PyErr_Occurred())
1494 err = -1;
1495 }
1496 }
1497 if (err) {
1498 /* Don't do anything else */
1499 }
1500 else {
1501 PyObject* moduleName;
1502 char* className;
1503 assert(PyExceptionClass_Check(type));
1504 className = PyExceptionClass_Name(type);
1505 if (className != NULL) {
1506 char *dot = strrchr(className, '.');
1507 if (dot != NULL)
1508 className = dot+1;
1509 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001510
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001511 moduleName = PyObject_GetAttrString(type, "__module__");
1512 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1513 {
1514 Py_DECREF(moduleName);
1515 err = PyFile_WriteString("<unknown>", f);
1516 }
1517 else {
1518 char* modstr = _PyUnicode_AsString(moduleName);
1519 if (modstr && strcmp(modstr, "builtins"))
1520 {
1521 err = PyFile_WriteString(modstr, f);
1522 err += PyFile_WriteString(".", f);
1523 }
1524 Py_DECREF(moduleName);
1525 }
1526 if (err == 0) {
1527 if (className == NULL)
1528 err = PyFile_WriteString("<unknown>", f);
1529 else
1530 err = PyFile_WriteString(className, f);
1531 }
1532 }
1533 if (err == 0 && (value != Py_None)) {
1534 PyObject *s = PyObject_Str(value);
1535 /* only print colon if the str() of the
1536 object is not the empty string
1537 */
1538 if (s == NULL)
1539 err = -1;
1540 else if (!PyUnicode_Check(s) ||
1541 PyUnicode_GetSize(s) != 0)
1542 err = PyFile_WriteString(": ", f);
1543 if (err == 0)
1544 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1545 Py_XDECREF(s);
1546 }
1547 /* try to write a newline in any case */
1548 err += PyFile_WriteString("\n", f);
1549 Py_XDECREF(tb);
1550 Py_DECREF(value);
1551 /* If an error happened here, don't show it.
1552 XXX This is wrong, but too many callers rely on this behavior. */
1553 if (err != 0)
1554 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001555}
1556
1557static const char *cause_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001558 "\nThe above exception was the direct cause "
1559 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001560
1561static const char *context_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001562 "\nDuring handling of the above exception, "
1563 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001564
1565static void
1566print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1567{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001568 int err = 0, res;
1569 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001570
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001571 if (seen != NULL) {
1572 /* Exception chaining */
1573 if (PySet_Add(seen, value) == -1)
1574 PyErr_Clear();
1575 else if (PyExceptionInstance_Check(value)) {
1576 cause = PyException_GetCause(value);
1577 context = PyException_GetContext(value);
1578 if (cause) {
1579 res = PySet_Contains(seen, cause);
1580 if (res == -1)
1581 PyErr_Clear();
1582 if (res == 0) {
1583 print_exception_recursive(
1584 f, cause, seen);
1585 err |= PyFile_WriteString(
1586 cause_message, f);
1587 }
1588 }
1589 else if (context) {
1590 res = PySet_Contains(seen, context);
1591 if (res == -1)
1592 PyErr_Clear();
1593 if (res == 0) {
1594 print_exception_recursive(
1595 f, context, seen);
1596 err |= PyFile_WriteString(
1597 context_message, f);
1598 }
1599 }
1600 Py_XDECREF(context);
1601 Py_XDECREF(cause);
1602 }
1603 }
1604 print_exception(f, value);
1605 if (err != 0)
1606 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001607}
1608
Thomas Wouters477c8d52006-05-27 19:21:47 +00001609void
1610PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001611{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001612 PyObject *seen;
1613 PyObject *f = PySys_GetObject("stderr");
1614 if (f == Py_None) {
1615 /* pass */
1616 }
1617 else if (f == NULL) {
1618 _PyObject_Dump(value);
1619 fprintf(stderr, "lost sys.stderr\n");
1620 }
1621 else {
1622 /* We choose to ignore seen being possibly NULL, and report
1623 at least the main exception (it could be a MemoryError).
1624 */
1625 seen = PySet_New(NULL);
1626 if (seen == NULL)
1627 PyErr_Clear();
1628 print_exception_recursive(f, value, seen);
1629 Py_XDECREF(seen);
1630 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001631}
1632
Guido van Rossum82598051997-03-05 00:20:32 +00001633PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001634PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001635 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001636{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001637 PyObject *ret = NULL;
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 Pitrou7f14f0d2010-05-09 16:14:21 +00001643 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1644 if (mod != NULL)
1645 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1646 PyArena_Free(arena);
1647 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001648}
1649
1650PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001651PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001652 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001653{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001654 PyObject *ret;
1655 mod_ty mod;
1656 PyArena *arena = PyArena_New();
1657 if (arena == NULL)
1658 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001659
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001660 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1661 flags, NULL, arena);
1662 if (closeit)
1663 fclose(fp);
1664 if (mod == NULL) {
1665 PyArena_Free(arena);
1666 return NULL;
1667 }
1668 ret = run_mod(mod, filename, globals, locals, flags, arena);
1669 PyArena_Free(arena);
1670 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001671}
1672
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001673static void
1674flush_io(void)
1675{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001676 PyObject *f, *r;
1677 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001678
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001679 /* Save the current exception */
1680 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001681
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001682 f = PySys_GetObject("stderr");
1683 if (f != NULL) {
1684 r = PyObject_CallMethod(f, "flush", "");
1685 if (r)
1686 Py_DECREF(r);
1687 else
1688 PyErr_Clear();
1689 }
1690 f = PySys_GetObject("stdout");
1691 if (f != NULL) {
1692 r = PyObject_CallMethod(f, "flush", "");
1693 if (r)
1694 Py_DECREF(r);
1695 else
1696 PyErr_Clear();
1697 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001698
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001699 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001700}
1701
Guido van Rossum82598051997-03-05 00:20:32 +00001702static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001703run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001704 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001705{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001706 PyCodeObject *co;
1707 PyObject *v;
1708 co = PyAST_Compile(mod, filename, flags, arena);
1709 if (co == NULL)
1710 return NULL;
1711 v = PyEval_EvalCode(co, globals, locals);
1712 Py_DECREF(co);
1713 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001714}
1715
Guido van Rossum82598051997-03-05 00:20:32 +00001716static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001717run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001718 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001719{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001720 PyCodeObject *co;
1721 PyObject *v;
1722 long magic;
1723 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001724
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001725 magic = PyMarshal_ReadLongFromFile(fp);
1726 if (magic != PyImport_GetMagicNumber()) {
1727 PyErr_SetString(PyExc_RuntimeError,
1728 "Bad magic number in .pyc file");
1729 return NULL;
1730 }
1731 (void) PyMarshal_ReadLongFromFile(fp);
1732 v = PyMarshal_ReadLastObjectFromFile(fp);
1733 fclose(fp);
1734 if (v == NULL || !PyCode_Check(v)) {
1735 Py_XDECREF(v);
1736 PyErr_SetString(PyExc_RuntimeError,
1737 "Bad code object in .pyc file");
1738 return NULL;
1739 }
1740 co = (PyCodeObject *)v;
1741 v = PyEval_EvalCode(co, globals, locals);
1742 if (v && flags)
1743 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1744 Py_DECREF(co);
1745 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001746}
1747
Guido van Rossum82598051997-03-05 00:20:32 +00001748PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001749Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001750 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001751{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001752 PyCodeObject *co;
1753 mod_ty mod;
1754 PyArena *arena = PyArena_New();
1755 if (arena == NULL)
1756 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001757
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001758 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1759 if (mod == NULL) {
1760 PyArena_Free(arena);
1761 return NULL;
1762 }
1763 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1764 PyObject *result = PyAST_mod2obj(mod);
1765 PyArena_Free(arena);
1766 return result;
1767 }
1768 co = PyAST_Compile(mod, filename, flags, arena);
1769 PyArena_Free(arena);
1770 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001771}
1772
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001773struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001774Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001775{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001776 struct symtable *st;
1777 mod_ty mod;
1778 PyCompilerFlags flags;
1779 PyArena *arena = PyArena_New();
1780 if (arena == NULL)
1781 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001782
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001783 flags.cf_flags = 0;
1784 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1785 if (mod == NULL) {
1786 PyArena_Free(arena);
1787 return NULL;
1788 }
1789 st = PySymtable_Build(mod, filename, 0);
1790 PyArena_Free(arena);
1791 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001792}
1793
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794/* Preferred access to parser is through AST. */
1795mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001796PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001797 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001799 mod_ty mod;
1800 PyCompilerFlags localflags;
1801 perrdetail err;
1802 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001803
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001804 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1805 &_PyParser_Grammar, start, &err,
1806 &iflags);
1807 if (flags == NULL) {
1808 localflags.cf_flags = 0;
1809 flags = &localflags;
1810 }
1811 if (n) {
1812 flags->cf_flags |= iflags & PyCF_MASK;
1813 mod = PyAST_FromNode(n, flags, filename, arena);
1814 PyNode_Free(n);
1815 return mod;
1816 }
1817 else {
1818 err_input(&err);
1819 return NULL;
1820 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821}
1822
1823mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001824PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001825 int start, char *ps1,
1826 char *ps2, PyCompilerFlags *flags, int *errcode,
1827 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001828{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001829 mod_ty mod;
1830 PyCompilerFlags localflags;
1831 perrdetail err;
1832 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001833
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001834 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1835 &_PyParser_Grammar,
1836 start, ps1, ps2, &err, &iflags);
1837 if (flags == NULL) {
1838 localflags.cf_flags = 0;
1839 flags = &localflags;
1840 }
1841 if (n) {
1842 flags->cf_flags |= iflags & PyCF_MASK;
1843 mod = PyAST_FromNode(n, flags, filename, arena);
1844 PyNode_Free(n);
1845 return mod;
1846 }
1847 else {
1848 err_input(&err);
1849 if (errcode)
1850 *errcode = err.error;
1851 return NULL;
1852 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001853}
1854
Guido van Rossuma110aa61994-08-29 12:50:44 +00001855/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001856
Guido van Rossuma110aa61994-08-29 12:50:44 +00001857node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001858PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001859{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001860 perrdetail err;
1861 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1862 &_PyParser_Grammar,
1863 start, NULL, NULL, &err, flags);
1864 if (n == NULL)
1865 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001866
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001867 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001868}
1869
Guido van Rossuma110aa61994-08-29 12:50:44 +00001870/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001871
Guido van Rossuma110aa61994-08-29 12:50:44 +00001872node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001873PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001874{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001875 perrdetail err;
1876 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1877 start, &err, flags);
1878 if (n == NULL)
1879 err_input(&err);
1880 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001881}
1882
1883node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001884PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001885 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001886{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001887 perrdetail err;
1888 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1889 &_PyParser_Grammar, start, &err, flags);
1890 if (n == NULL)
1891 err_input(&err);
1892 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001893}
1894
1895node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001896PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001897{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001898 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001899}
1900
Guido van Rossum66ebd912003-04-17 16:02:26 +00001901/* May want to move a more generalized form of this to parsetok.c or
1902 even parser modules. */
1903
1904void
1905PyParser_SetError(perrdetail *err)
1906{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001907 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001908}
1909
Guido van Rossuma110aa61994-08-29 12:50:44 +00001910/* Set the error appropriate to the given input error code (see errcode.h) */
1911
1912static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001913err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001914{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001915 PyObject *v, *w, *errtype, *errtext;
1916 PyObject* u = NULL;
Victor Stinner15244f72010-10-19 01:22:07 +00001917 PyObject *filename;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001918 char *msg = NULL;
Victor Stinner15244f72010-10-19 01:22:07 +00001919
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001920 errtype = PyExc_SyntaxError;
1921 switch (err->error) {
1922 case E_ERROR:
1923 return;
1924 case E_SYNTAX:
1925 errtype = PyExc_IndentationError;
1926 if (err->expected == INDENT)
1927 msg = "expected an indented block";
1928 else if (err->token == INDENT)
1929 msg = "unexpected indent";
1930 else if (err->token == DEDENT)
1931 msg = "unexpected unindent";
1932 else {
1933 errtype = PyExc_SyntaxError;
1934 msg = "invalid syntax";
1935 }
1936 break;
1937 case E_TOKEN:
1938 msg = "invalid token";
1939 break;
1940 case E_EOFS:
1941 msg = "EOF while scanning triple-quoted string literal";
1942 break;
1943 case E_EOLS:
1944 msg = "EOL while scanning string literal";
1945 break;
1946 case E_INTR:
1947 if (!PyErr_Occurred())
1948 PyErr_SetNone(PyExc_KeyboardInterrupt);
1949 goto cleanup;
1950 case E_NOMEM:
1951 PyErr_NoMemory();
1952 goto cleanup;
1953 case E_EOF:
1954 msg = "unexpected EOF while parsing";
1955 break;
1956 case E_TABSPACE:
1957 errtype = PyExc_TabError;
1958 msg = "inconsistent use of tabs and spaces in indentation";
1959 break;
1960 case E_OVERFLOW:
1961 msg = "expression too long";
1962 break;
1963 case E_DEDENT:
1964 errtype = PyExc_IndentationError;
1965 msg = "unindent does not match any outer indentation level";
1966 break;
1967 case E_TOODEEP:
1968 errtype = PyExc_IndentationError;
1969 msg = "too many levels of indentation";
1970 break;
1971 case E_DECODE: {
1972 PyObject *type, *value, *tb;
1973 PyErr_Fetch(&type, &value, &tb);
1974 if (value != NULL) {
1975 u = PyObject_Str(value);
1976 if (u != NULL) {
1977 msg = _PyUnicode_AsString(u);
1978 }
1979 }
1980 if (msg == NULL)
1981 msg = "unknown decode error";
1982 Py_XDECREF(type);
1983 Py_XDECREF(value);
1984 Py_XDECREF(tb);
1985 break;
1986 }
1987 case E_LINECONT:
1988 msg = "unexpected character after line continuation character";
1989 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001990
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001991 case E_IDENTIFIER:
1992 msg = "invalid character in identifier";
1993 break;
1994 default:
1995 fprintf(stderr, "error=%d\n", err->error);
1996 msg = "unknown parsing error";
1997 break;
1998 }
1999 /* err->text may not be UTF-8 in case of decoding errors.
2000 Explicitly convert to an object. */
2001 if (!err->text) {
2002 errtext = Py_None;
2003 Py_INCREF(Py_None);
2004 } else {
2005 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2006 "replace");
2007 }
Victor Stinner15244f72010-10-19 01:22:07 +00002008 if (err->filename != NULL)
2009 filename = PyUnicode_DecodeFSDefault(err->filename);
2010 else {
2011 Py_INCREF(Py_None);
2012 filename = Py_None;
2013 }
2014 if (filename != NULL)
2015 v = Py_BuildValue("(NiiN)", filename,
2016 err->lineno, err->offset, errtext);
2017 else
2018 v = NULL;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002019 w = NULL;
2020 if (v != NULL)
2021 w = Py_BuildValue("(sO)", msg, v);
2022 Py_XDECREF(u);
2023 Py_XDECREF(v);
2024 PyErr_SetObject(errtype, w);
2025 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002026cleanup:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002027 if (err->text != NULL) {
2028 PyObject_FREE(err->text);
2029 err->text = NULL;
2030 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002031}
2032
2033/* Print fatal error message and abort */
2034
2035void
Tim Peters7c321a82002-07-09 02:57:01 +00002036Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002037{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002038 fprintf(stderr, "Fatal Python error: %s\n", msg);
2039 fflush(stderr); /* it helps in Windows debug build */
2040 if (PyErr_Occurred()) {
Victor Stinner93362d42010-06-08 21:05:20 +00002041 PyErr_PrintEx(0);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002042 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002043#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002044 {
2045 size_t len = strlen(msg);
2046 WCHAR* buffer;
2047 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002048
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002049 /* Convert the message to wchar_t. This uses a simple one-to-one
2050 conversion, assuming that the this error message actually uses ASCII
2051 only. If this ceases to be true, we will have to convert. */
2052 buffer = alloca( (len+1) * (sizeof *buffer));
2053 for( i=0; i<=len; ++i)
2054 buffer[i] = msg[i];
2055 OutputDebugStringW(L"Fatal Python error: ");
2056 OutputDebugStringW(buffer);
2057 OutputDebugStringW(L"\n");
2058 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002059#ifdef _DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002060 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002061#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002062#endif /* MS_WINDOWS */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002063 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002064}
2065
2066/* Clean up and exit */
2067
Guido van Rossuma110aa61994-08-29 12:50:44 +00002068#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002069#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002070#endif
2071
Collin Winter670e6922007-03-21 02:57:17 +00002072static void (*pyexitfunc)(void) = NULL;
2073/* For the atexit module. */
2074void _Py_PyAtExit(void (*func)(void))
2075{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002076 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002077}
2078
2079static void
2080call_py_exitfuncs(void)
2081{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002082 if (pyexitfunc == NULL)
2083 return;
Collin Winter670e6922007-03-21 02:57:17 +00002084
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002085 (*pyexitfunc)();
2086 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002087}
2088
Antoine Pitroucefb3162009-10-20 22:08:36 +00002089/* Wait until threading._shutdown completes, provided
2090 the threading module was imported in the first place.
2091 The shutdown routine will wait until all non-daemon
2092 "threading" threads have completed. */
2093static void
2094wait_for_thread_shutdown(void)
2095{
2096#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002097 PyObject *result;
2098 PyThreadState *tstate = PyThreadState_GET();
2099 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2100 "threading");
2101 if (threading == NULL) {
2102 /* threading not imported */
2103 PyErr_Clear();
2104 return;
2105 }
2106 result = PyObject_CallMethod(threading, "_shutdown", "");
2107 if (result == NULL) {
2108 PyErr_WriteUnraisable(threading);
2109 }
2110 else {
2111 Py_DECREF(result);
2112 }
2113 Py_DECREF(threading);
Antoine Pitroucefb3162009-10-20 22:08:36 +00002114#endif
2115}
2116
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002117#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002118static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002119static int nexitfuncs = 0;
2120
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002121int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002122{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002123 if (nexitfuncs >= NEXITFUNCS)
2124 return -1;
2125 exitfuncs[nexitfuncs++] = func;
2126 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002127}
2128
Guido van Rossumcc283f51997-08-05 02:22:03 +00002129static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002130call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002131{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002132 while (nexitfuncs > 0)
2133 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002134
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002135 fflush(stdout);
2136 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002137}
2138
2139void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002140Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002141{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002142 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002143
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002144 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002145}
2146
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002147static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002148initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002149{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002150#ifdef SIGPIPE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002151 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002152#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002153#ifdef SIGXFZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002154 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002155#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002156#ifdef SIGXFSZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002157 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002158#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002159 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002160}
2161
Guido van Rossum7433b121997-02-14 19:45:36 +00002162
2163/*
2164 * The file descriptor fd is considered ``interactive'' if either
2165 * a) isatty(fd) is TRUE, or
2166 * b) the -i flag was given, and the filename associated with
2167 * the descriptor is NULL or "<stdin>" or "???".
2168 */
2169int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002170Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002171{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002172 if (isatty((int)fileno(fp)))
2173 return 1;
2174 if (!Py_InteractiveFlag)
2175 return 0;
2176 return (filename == NULL) ||
2177 (strcmp(filename, "<stdin>") == 0) ||
2178 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002179}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002180
2181
Tim Petersd08e3822003-04-17 15:24:21 +00002182#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002183#if defined(WIN32) && defined(_MSC_VER)
2184
2185/* Stack checking for Microsoft C */
2186
2187#include <malloc.h>
2188#include <excpt.h>
2189
Fred Drakee8de31c2000-08-31 05:38:39 +00002190/*
2191 * Return non-zero when we run out of memory on the stack; zero otherwise.
2192 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002193int
Fred Drake399739f2000-08-31 05:52:44 +00002194PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002195{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002196 __try {
2197 /* alloca throws a stack overflow exception if there's
2198 not enough space left on the stack */
2199 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2200 return 0;
2201 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2202 EXCEPTION_EXECUTE_HANDLER :
2203 EXCEPTION_CONTINUE_SEARCH) {
2204 int errcode = _resetstkoflw();
2205 if (errcode == 0)
2206 {
2207 Py_FatalError("Could not reset the stack!");
2208 }
2209 }
2210 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002211}
2212
2213#endif /* WIN32 && _MSC_VER */
2214
2215/* Alternate implementations can be added here... */
2216
2217#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002218
2219
2220/* Wrappers around sigaction() or signal(). */
2221
2222PyOS_sighandler_t
2223PyOS_getsig(int sig)
2224{
2225#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002226 struct sigaction context;
2227 if (sigaction(sig, NULL, &context) == -1)
2228 return SIG_ERR;
2229 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002230#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002231 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002232/* Special signal handling for the secure CRT in Visual Studio 2005 */
2233#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002234 switch (sig) {
2235 /* Only these signals are valid */
2236 case SIGINT:
2237 case SIGILL:
2238 case SIGFPE:
2239 case SIGSEGV:
2240 case SIGTERM:
2241 case SIGBREAK:
2242 case SIGABRT:
2243 break;
2244 /* Don't call signal() with other values or it will assert */
2245 default:
2246 return SIG_ERR;
2247 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002248#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002249 handler = signal(sig, SIG_IGN);
2250 if (handler != SIG_ERR)
2251 signal(sig, handler);
2252 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002253#endif
2254}
2255
2256PyOS_sighandler_t
2257PyOS_setsig(int sig, PyOS_sighandler_t handler)
2258{
2259#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002260 /* Some code in Modules/signalmodule.c depends on sigaction() being
2261 * used here if HAVE_SIGACTION is defined. Fix that if this code
2262 * changes to invalidate that assumption.
2263 */
2264 struct sigaction context, ocontext;
2265 context.sa_handler = handler;
2266 sigemptyset(&context.sa_mask);
2267 context.sa_flags = 0;
2268 if (sigaction(sig, &context, &ocontext) == -1)
2269 return SIG_ERR;
2270 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002271#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002272 PyOS_sighandler_t oldhandler;
2273 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002274#ifdef HAVE_SIGINTERRUPT
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002275 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002276#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002277 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002278#endif
2279}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280
2281/* Deprecated C API functions still provided for binary compatiblity */
2282
2283#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002284PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002285PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2286{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002287 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288}
2289
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002290#undef PyParser_SimpleParseString
2291PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002292PyParser_SimpleParseString(const char *str, int start)
2293{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002294 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002295}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002296
2297#undef PyRun_AnyFile
2298PyAPI_FUNC(int)
2299PyRun_AnyFile(FILE *fp, const char *name)
2300{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002301 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002302}
2303
2304#undef PyRun_AnyFileEx
2305PyAPI_FUNC(int)
2306PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2307{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002308 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002309}
2310
2311#undef PyRun_AnyFileFlags
2312PyAPI_FUNC(int)
2313PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2314{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002315 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002316}
2317
2318#undef PyRun_File
2319PyAPI_FUNC(PyObject *)
2320PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2321{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002322 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002323}
2324
2325#undef PyRun_FileEx
2326PyAPI_FUNC(PyObject *)
2327PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2328{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002329 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002330}
2331
2332#undef PyRun_FileFlags
2333PyAPI_FUNC(PyObject *)
2334PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002335 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002336{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002337 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002338}
2339
2340#undef PyRun_SimpleFile
2341PyAPI_FUNC(int)
2342PyRun_SimpleFile(FILE *f, const char *p)
2343{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002344 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002345}
2346
2347#undef PyRun_SimpleFileEx
2348PyAPI_FUNC(int)
2349PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2350{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002351 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002352}
2353
2354
2355#undef PyRun_String
2356PyAPI_FUNC(PyObject *)
2357PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2358{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002359 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002360}
2361
2362#undef PyRun_SimpleString
2363PyAPI_FUNC(int)
2364PyRun_SimpleString(const char *s)
2365{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002366 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002367}
2368
2369#undef Py_CompileString
2370PyAPI_FUNC(PyObject *)
2371Py_CompileString(const char *str, const char *p, int s)
2372{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002373 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002374}
2375
2376#undef PyRun_InteractiveOne
2377PyAPI_FUNC(int)
2378PyRun_InteractiveOne(FILE *f, const char *p)
2379{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002380 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002381}
2382
2383#undef PyRun_InteractiveLoop
2384PyAPI_FUNC(int)
2385PyRun_InteractiveLoop(FILE *f, const char *p)
2386{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002387 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002388}
2389
2390#ifdef __cplusplus
2391}
2392#endif