blob: 4474e79b0f4eef313fbaba88631caf3772fa4304 [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);
Georg Brandl2daf6ae2012-02-20 19:54:16 +010076extern void _PyRandom_Init(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000077
Mark Hammond8d98d2c2003-04-19 15:41:53 +000078#ifdef WITH_THREAD
79extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
80extern void _PyGILState_Fini(void);
81#endif /* WITH_THREAD */
82
Guido van Rossum82598051997-03-05 00:20:32 +000083int Py_DebugFlag; /* Needed by parser.c */
84int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000085int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020086int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000087int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000088int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000089int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000090int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000091int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000092int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000094int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +010095int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000096
Christian Heimes33fe8092008-04-13 13:53:33 +000097/* PyModule_GetWarningsModule is no longer necessary as of 2.6
98since _warnings is builtin. This API should not be used. */
99PyObject *
100PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000101{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000102 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000103}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000104
Guido van Rossum25ce5661997-08-02 03:10:38 +0000105static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000106
Thomas Wouters7e474022000-07-16 12:04:32 +0000107/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000108
109int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000110Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000112 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000113}
114
Guido van Rossum25ce5661997-08-02 03:10:38 +0000115/* Global initializations. Can be undone by Py_Finalize(). Don't
116 call this twice without an intervening Py_Finalize() call. When
117 initializations fail, a fatal error is issued and the function does
118 not return. On return, the first thread and interpreter state have
119 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121 Locking: you must hold the interpreter lock while calling this.
122 (If the lock has not yet been initialized, that's equivalent to
123 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000124
Guido van Rossum25ce5661997-08-02 03:10:38 +0000125*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000126
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000127static int
128add_flag(int flag, const char *envs)
129{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000130 int env = atoi(envs);
131 if (flag < env)
132 flag = env;
133 if (flag < 1)
134 flag = 1;
135 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000136}
137
Christian Heimes5833a2f2008-10-30 21:40:04 +0000138#if defined(HAVE_LANGINFO_H) && defined(CODESET)
139static char*
140get_codeset(void)
141{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000142 char* codeset;
143 PyObject *codec, *name;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000144
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000145 codeset = nl_langinfo(CODESET);
146 if (!codeset || codeset[0] == '\0')
147 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000148
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000149 codec = _PyCodec_Lookup(codeset);
150 if (!codec)
151 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000152
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000153 name = PyObject_GetAttrString(codec, "name");
154 Py_CLEAR(codec);
155 if (!name)
156 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000157
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000158 codeset = strdup(_PyUnicode_AsString(name));
159 Py_DECREF(name);
160 return codeset;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000161
162error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000163 Py_XDECREF(codec);
164 PyErr_Clear();
165 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000166}
167#endif
168
Guido van Rossuma027efa1997-05-05 20:56:21 +0000169void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000170Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000171{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000172 PyInterpreterState *interp;
173 PyThreadState *tstate;
174 PyObject *bimod, *sysmod, *pstderr;
175 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000176#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000177 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000178#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000179 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000180
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000181 if (initialized)
182 return;
183 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000184
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000185#ifdef HAVE_SETLOCALE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000186 /* Set up the LC_CTYPE locale, so we can obtain
187 the locale's charset without having to switch
188 locales. */
189 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000190#endif
191
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000192 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
193 Py_DebugFlag = add_flag(Py_DebugFlag, p);
194 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
195 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
196 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
197 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
198 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
199 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100200 /* The variable is only tested for existence here; _PyRandom_Init will
201 check its value further. */
202 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
203 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
204
205 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000206
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000207 interp = PyInterpreterState_New();
208 if (interp == NULL)
209 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000210
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000211 tstate = PyThreadState_New(interp);
212 if (tstate == NULL)
213 Py_FatalError("Py_Initialize: can't make first thread");
214 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000215
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000216 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000217
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000218 if (!_PyFrame_Init())
219 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000220
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000221 if (!_PyLong_Init())
222 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000223
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000224 if (!PyByteArray_Init())
225 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000226
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000227 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000228
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000229 interp->modules = PyDict_New();
230 if (interp->modules == NULL)
231 Py_FatalError("Py_Initialize: can't make modules dictionary");
232 interp->modules_reloading = PyDict_New();
233 if (interp->modules_reloading == NULL)
234 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000235
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000236 /* Init Unicode implementation; relies on the codec registry */
237 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000238
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000239 bimod = _PyBuiltin_Init();
240 if (bimod == NULL)
241 Py_FatalError("Py_Initialize: can't initialize builtins modules");
242 _PyImport_FixupExtension(bimod, "builtins", "builtins");
243 interp->builtins = PyModule_GetDict(bimod);
244 if (interp->builtins == NULL)
245 Py_FatalError("Py_Initialize: can't initialize builtins dict");
246 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000247
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000248 /* initialize builtin exceptions */
249 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000250
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000251 sysmod = _PySys_Init();
252 if (sysmod == NULL)
253 Py_FatalError("Py_Initialize: can't initialize sys");
254 interp->sysdict = PyModule_GetDict(sysmod);
255 if (interp->sysdict == NULL)
256 Py_FatalError("Py_Initialize: can't initialize sys dict");
257 Py_INCREF(interp->sysdict);
258 _PyImport_FixupExtension(sysmod, "sys", "sys");
259 PySys_SetPath(Py_GetPath());
260 PyDict_SetItemString(interp->sysdict, "modules",
261 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000262
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000263 /* Set up a preliminary stderr printer until we have enough
264 infrastructure for the io module in place. */
265 pstderr = PyFile_NewStdPrinter(fileno(stderr));
266 if (pstderr == NULL)
267 Py_FatalError("Py_Initialize: can't set preliminary stderr");
268 PySys_SetObject("stderr", pstderr);
269 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamoto3d897512010-10-30 15:43:30 +0000270 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000271
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000272 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000273
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000274 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000275
Victor Stinner148051a2010-05-20 21:00:34 +0000276 /* Initialize _warnings. */
277 _PyWarnings_Init();
278
Martin v. Löwis011e8422009-05-05 04:43:17 +0000279#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000280 /* On Unix, set the file system encoding according to the
281 user's preference, if the CODESET names a well-known
282 Python codec, and Py_FileSystemDefaultEncoding isn't
283 initialized by other means. Also set the encoding of
284 stdin and stdout if these are terminals. */
Martin v. Löwis011e8422009-05-05 04:43:17 +0000285
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000286 codeset = get_codeset();
287 if (codeset) {
288 if (!Py_FileSystemDefaultEncoding)
289 Py_FileSystemDefaultEncoding = codeset;
290 else
291 free(codeset);
292 }
Martin v. Löwis011e8422009-05-05 04:43:17 +0000293#endif
294
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000295 if (install_sigs)
296 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000297
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000298 /* Initialize warnings. */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000299 if (PySys_HasWarnOptions()) {
300 PyObject *warnings_module = PyImport_ImportModule("warnings");
301 if (!warnings_module)
302 PyErr_Clear();
303 Py_XDECREF(warnings_module);
304 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000305
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000306 initmain(); /* Module __main__ */
307 if (initstdio() < 0)
308 Py_FatalError(
309 "Py_Initialize: can't initialize sys standard streams");
310
311 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000312#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000313 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000314#endif /* WITH_THREAD */
Victor Stinnerffbc2f62010-03-21 21:48:45 +0000315
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000316 if (!Py_NoSiteFlag)
317 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000318}
319
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000320void
321Py_Initialize(void)
322{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000323 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000324}
325
326
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000327#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000328extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000329#endif
330
Guido van Rossume8432ac2007-07-09 15:04:50 +0000331/* Flush stdout and stderr */
332
Neal Norwitz2bad9702007-08-27 06:19:22 +0000333static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000334flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000335{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000336 PyObject *fout = PySys_GetObject("stdout");
337 PyObject *ferr = PySys_GetObject("stderr");
338 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000339
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000340 if (fout != NULL && fout != Py_None) {
341 tmp = PyObject_CallMethod(fout, "flush", "");
342 if (tmp == NULL)
Antoine Pitroub61d5c92010-08-08 20:49:19 +0000343 PyErr_WriteUnraisable(fout);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000344 else
345 Py_DECREF(tmp);
346 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000347
Victor Stinnerebb5a882010-05-14 01:03:14 +0000348 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000349 tmp = PyObject_CallMethod(ferr, "flush", "");
350 if (tmp == NULL)
351 PyErr_Clear();
352 else
353 Py_DECREF(tmp);
354 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000355}
356
Guido van Rossum25ce5661997-08-02 03:10:38 +0000357/* Undo the effect of Py_Initialize().
358
359 Beware: if multiple interpreter and/or thread states exist, these
360 are not wiped out; only the current thread and interpreter state
361 are deleted. But since everything else is deleted, those other
362 interpreter and thread states should no longer be used.
363
364 (XXX We should do better, e.g. wipe out all interpreters and
365 threads.)
366
367 Locking: as above.
368
369*/
370
371void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000372Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000373{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000374 PyInterpreterState *interp;
375 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000376
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000377 if (!initialized)
378 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000379
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000380 wait_for_thread_shutdown();
Antoine Pitroucefb3162009-10-20 22:08:36 +0000381
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000382 /* The interpreter is still entirely intact at this point, and the
383 * exit funcs may be relying on that. In particular, if some thread
384 * or exit func is still waiting to do an import, the import machinery
385 * expects Py_IsInitialized() to return true. So don't say the
386 * interpreter is uninitialized until after the exit funcs have run.
387 * Note that Threading.py uses an exit func to do a join on all the
388 * threads created thru it, so this also protects pending imports in
389 * the threads created via Threading.
390 */
391 call_py_exitfuncs();
392 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000393
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000394 /* Flush stdout+stderr */
395 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000396
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000397 /* Get current thread state and interpreter pointer */
398 tstate = PyThreadState_GET();
399 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000400
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000401 /* Disable signal handling */
402 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000403
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000404 /* Clear type lookup cache */
405 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000406
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000407 /* Collect garbage. This may call finalizers; it's nice to call these
408 * before all modules are destroyed.
409 * XXX If a __del__ or weakref callback is triggered here, and tries to
410 * XXX import a module, bad things can happen, because Python no
411 * XXX longer believes it's initialized.
412 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
413 * XXX is easy to provoke that way. I've also seen, e.g.,
414 * XXX Exception exceptions.ImportError: 'No module named sha'
415 * XXX in <function callback at 0x008F5718> ignored
416 * XXX but I'm unclear on exactly how that one happens. In any case,
417 * XXX I haven't seen a real-life report of either of these.
418 */
419 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000420#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000421 /* With COUNT_ALLOCS, it helps to run GC multiple times:
422 each collection might release some types from the type
423 list, so they become garbage. */
424 while (PyGC_Collect() > 0)
425 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000426#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000427
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000428 /* Destroy all modules */
429 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000430
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000431 /* Flush stdout+stderr (again, in case more was printed) */
432 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000433
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000434 /* Collect final garbage. This disposes of cycles created by
435 * new-style class definitions, for example.
436 * XXX This is disabled because it caused too many problems. If
437 * XXX a __del__ or weakref callback triggers here, Python code has
438 * XXX a hard time running, because even the sys module has been
439 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
440 * XXX One symptom is a sequence of information-free messages
441 * XXX coming from threads (if a __del__ or callback is invoked,
442 * XXX other threads can execute too, and any exception they encounter
443 * XXX triggers a comedy of errors as subsystem after subsystem
444 * XXX fails to find what it *expects* to find in sys to help report
445 * XXX the exception and consequent unexpected failures). I've also
446 * XXX seen segfaults then, after adding print statements to the
447 * XXX Python code getting called.
448 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000449#if 0
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000450 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000451#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000452
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000453 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
454 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000455
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000456 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000457#ifdef COUNT_ALLOCS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000458 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000459#endif
460
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000461 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000462
Tim Peters9cf25ce2003-04-17 15:21:01 +0000463#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000464 /* Display all objects still alive -- this can invoke arbitrary
465 * __repr__ overrides, so requires a mostly-intact interpreter.
466 * Alas, a lot of stuff may still be alive now that will be cleaned
467 * up later.
468 */
469 if (Py_GETENV("PYTHONDUMPREFS"))
470 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000471#endif /* Py_TRACE_REFS */
472
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000473 /* Clear interpreter state */
474 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000475
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000476 /* Now we decref the exception classes. After this point nothing
477 can raise an exception. That's okay, because each Fini() method
478 below has been checked to make sure no exceptions are ever
479 raised.
480 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000481
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000482 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000483
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000484 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000485#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000486 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000487#endif /* WITH_THREAD */
488
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000489 /* Delete current thread */
490 PyThreadState_Swap(NULL);
491 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000492
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000493 /* Sundry finalizers */
494 PyMethod_Fini();
495 PyFrame_Fini();
496 PyCFunction_Fini();
497 PyTuple_Fini();
498 PyList_Fini();
499 PySet_Fini();
500 PyBytes_Fini();
501 PyByteArray_Fini();
502 PyLong_Fini();
503 PyFloat_Fini();
504 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000505
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000506 /* Cleanup Unicode implementation */
507 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000508
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000509 /* reset file system default encoding */
510 if (!Py_HasFileSystemDefaultEncoding) {
511 free((char*)Py_FileSystemDefaultEncoding);
512 Py_FileSystemDefaultEncoding = NULL;
513 }
Christian Heimesc8967002007-11-30 10:18:26 +0000514
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000515 /* XXX Still allocated:
516 - various static ad-hoc pointers to interned strings
517 - int and float free list blocks
518 - whatever various modules and libraries allocate
519 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000520
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000521 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000522
Tim Peters269b2a62003-04-17 19:52:29 +0000523#ifdef Py_TRACE_REFS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000524 /* Display addresses (& refcnts) of all objects still alive.
525 * An address can be used to find the repr of the object, printed
526 * above by _Py_PrintReferences.
527 */
528 if (Py_GETENV("PYTHONDUMPREFS"))
529 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000530#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000531#ifdef PYMALLOC_DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000532 if (Py_GETENV("PYTHONMALLOCSTATS"))
533 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000534#endif
535
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000536 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000537}
538
539/* Create and initialize a new interpreter and thread, and return the
540 new thread. This requires that Py_Initialize() has been called
541 first.
542
543 Unsuccessful initialization yields a NULL pointer. Note that *no*
544 exception information is available even in this case -- the
545 exception information is held in the thread, and there is no
546 thread.
547
548 Locking: as above.
549
550*/
551
552PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000553Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000554{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000555 PyInterpreterState *interp;
556 PyThreadState *tstate, *save_tstate;
557 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000558
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000559 if (!initialized)
560 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000562 interp = PyInterpreterState_New();
563 if (interp == NULL)
564 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000566 tstate = PyThreadState_New(interp);
567 if (tstate == NULL) {
568 PyInterpreterState_Delete(interp);
569 return NULL;
570 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000571
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000572 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000574 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000575
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000576 interp->modules = PyDict_New();
577 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000578
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000579 bimod = _PyImport_FindExtension("builtins", "builtins");
580 if (bimod != NULL) {
581 interp->builtins = PyModule_GetDict(bimod);
582 if (interp->builtins == NULL)
583 goto handle_error;
584 Py_INCREF(interp->builtins);
585 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000586
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000587 /* initialize builtin exceptions */
588 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000589
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000590 sysmod = _PyImport_FindExtension("sys", "sys");
591 if (bimod != NULL && sysmod != NULL) {
592 PyObject *pstderr;
593 interp->sysdict = PyModule_GetDict(sysmod);
594 if (interp->sysdict == NULL)
595 goto handle_error;
596 Py_INCREF(interp->sysdict);
597 PySys_SetPath(Py_GetPath());
598 PyDict_SetItemString(interp->sysdict, "modules",
599 interp->modules);
600 /* Set up a preliminary stderr printer until we have enough
601 infrastructure for the io module in place. */
602 pstderr = PyFile_NewStdPrinter(fileno(stderr));
603 if (pstderr == NULL)
604 Py_FatalError("Py_Initialize: can't set preliminary stderr");
605 PySys_SetObject("stderr", pstderr);
606 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamoto3d897512010-10-30 15:43:30 +0000607 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000608
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000609 _PyImportHooks_Init();
610 if (initstdio() < 0)
611 Py_FatalError(
612 "Py_Initialize: can't initialize sys standard streams");
613 initmain();
614 if (!Py_NoSiteFlag)
615 initsite();
616 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000618 if (!PyErr_Occurred())
619 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000620
Thomas Wouters89f507f2006-12-13 04:49:30 +0000621handle_error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000622 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000623
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000624 PyErr_Print();
625 PyThreadState_Clear(tstate);
626 PyThreadState_Swap(save_tstate);
627 PyThreadState_Delete(tstate);
628 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000630 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631}
632
633/* Delete an interpreter and its last thread. This requires that the
634 given thread state is current, that the thread has no remaining
635 frames, and that it is its interpreter's only remaining thread.
636 It is a fatal error to violate these constraints.
637
638 (Py_Finalize() doesn't have these constraints -- it zaps
639 everything, regardless.)
640
641 Locking: as above.
642
643*/
644
645void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000646Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000647{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000648 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000650 if (tstate != PyThreadState_GET())
651 Py_FatalError("Py_EndInterpreter: thread is not current");
652 if (tstate->frame != NULL)
653 Py_FatalError("Py_EndInterpreter: thread still has a frame");
654 if (tstate != interp->tstate_head || tstate->next != NULL)
655 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000656
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000657 PyImport_Cleanup();
658 PyInterpreterState_Clear(interp);
659 PyThreadState_Swap(NULL);
660 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000661}
662
Martin v. Löwis790465f2008-04-05 20:41:37 +0000663static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000664
665void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000666Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000667{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000668 if (pn && *pn)
669 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000670}
671
Martin v. Löwis790465f2008-04-05 20:41:37 +0000672wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000673Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000674{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000675 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000676}
677
Martin v. Löwis790465f2008-04-05 20:41:37 +0000678static wchar_t *default_home = NULL;
679static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000680
681void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000682Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000683{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000684 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000685}
686
Martin v. Löwis790465f2008-04-05 20:41:37 +0000687wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000688Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000689{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000690 wchar_t *home = default_home;
691 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
692 char* chome = Py_GETENV("PYTHONHOME");
693 if (chome) {
694 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
695 if (r != (size_t)-1 && r <= PATH_MAX)
696 home = env_home;
697 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000698
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000699 }
700 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000701}
702
Guido van Rossum6135a871995-01-09 17:53:26 +0000703/* Create __main__ module */
704
705static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000706initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000707{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000708 PyObject *m, *d;
709 m = PyImport_AddModule("__main__");
710 if (m == NULL)
711 Py_FatalError("can't create __main__ module");
712 d = PyModule_GetDict(m);
713 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
714 PyObject *bimod = PyImport_ImportModule("builtins");
715 if (bimod == NULL ||
716 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
717 Py_FatalError("can't add __builtins__ to __main__");
718 Py_DECREF(bimod);
719 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000720}
721
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000722/* Import the site module (not into __main__ though) */
723
724static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000725initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000726{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000727 PyObject *m, *f;
728 m = PyImport_ImportModule("site");
729 if (m == NULL) {
730 f = PySys_GetObject("stderr");
731 if (f == NULL || f == Py_None)
732 return;
733 if (Py_VerboseFlag) {
Victor Stinner3aa6cea2010-10-23 08:50:36 +0000734 PyObject *type, *value, *traceback;
735 PyErr_Fetch(&type, &value, &traceback);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000736 PyFile_WriteString(
737 "'import site' failed; traceback:\n", f);
Victor Stinner3aa6cea2010-10-23 08:50:36 +0000738 PyErr_Restore(type, value, traceback);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000739 PyErr_Print();
740 }
741 else {
Victor Stinner3aa6cea2010-10-23 08:50:36 +0000742 PyErr_Clear();
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000743 PyFile_WriteString(
744 "'import site' failed; use -v for traceback\n", f);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000745 }
746 }
747 else {
748 Py_DECREF(m);
749 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000750}
751
Antoine Pitrou05608432009-01-09 18:53:14 +0000752static PyObject*
753create_stdio(PyObject* io,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000754 int fd, int write_mode, char* name,
755 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000756{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000757 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
758 const char* mode;
759 PyObject *line_buffering;
760 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000761
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000762 /* stdin is always opened in buffered mode, first because it shouldn't
763 make a difference in common use cases, second because TextIOWrapper
764 depends on the presence of a read1() method which only exists on
765 buffered streams.
766 */
767 if (Py_UnbufferedStdioFlag && write_mode)
768 buffering = 0;
769 else
770 buffering = -1;
771 if (write_mode)
772 mode = "wb";
773 else
774 mode = "rb";
775 buf = PyObject_CallMethod(io, "open", "isiOOOi",
776 fd, mode, buffering,
777 Py_None, Py_None, Py_None, 0);
778 if (buf == NULL)
779 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000780
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000781 if (buffering) {
782 raw = PyObject_GetAttrString(buf, "raw");
783 if (raw == NULL)
784 goto error;
785 }
786 else {
787 raw = buf;
788 Py_INCREF(raw);
789 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000790
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000791 text = PyUnicode_FromString(name);
792 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
793 goto error;
794 res = PyObject_CallMethod(raw, "isatty", "");
795 if (res == NULL)
796 goto error;
797 isatty = PyObject_IsTrue(res);
798 Py_DECREF(res);
799 if (isatty == -1)
800 goto error;
801 if (isatty || Py_UnbufferedStdioFlag)
802 line_buffering = Py_True;
803 else
804 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000805
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000806 Py_CLEAR(raw);
807 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000808
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000809 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
810 buf, encoding, errors,
811 "\n", line_buffering);
812 Py_CLEAR(buf);
813 if (stream == NULL)
814 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000815
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000816 if (write_mode)
817 mode = "w";
818 else
819 mode = "r";
820 text = PyUnicode_FromString(mode);
821 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
822 goto error;
823 Py_CLEAR(text);
824 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000825
826error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000827 Py_XDECREF(buf);
828 Py_XDECREF(stream);
829 Py_XDECREF(text);
830 Py_XDECREF(raw);
831 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000832}
833
Georg Brandl1a3284e2007-12-02 09:40:06 +0000834/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000835static int
836initstdio(void)
837{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000838 PyObject *iomod = NULL, *wrapper;
839 PyObject *bimod = NULL;
840 PyObject *m;
841 PyObject *std = NULL;
842 int status = 0, fd;
843 PyObject * encoding_attr;
844 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000845
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000846 /* Hack to avoid a nasty recursion issue when Python is invoked
847 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
848 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
849 goto error;
850 }
851 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000852
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000853 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
854 goto error;
855 }
856 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000857
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000858 if (!(bimod = PyImport_ImportModule("builtins"))) {
859 goto error;
860 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000861
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000862 if (!(iomod = PyImport_ImportModule("io"))) {
863 goto error;
864 }
865 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
866 goto error;
867 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000868
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000869 /* Set builtins.open */
870 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
871 goto error;
872 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000873
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000874 encoding = Py_GETENV("PYTHONIOENCODING");
875 errors = NULL;
876 if (encoding) {
877 encoding = strdup(encoding);
878 errors = strchr(encoding, ':');
879 if (errors) {
880 *errors = '\0';
881 errors++;
882 }
883 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000884
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000885 /* Set sys.stdin */
886 fd = fileno(stdin);
887 /* Under some conditions stdin, stdout and stderr may not be connected
888 * and fileno() may point to an invalid file descriptor. For example
889 * GUI apps don't have valid standard streams by default.
890 */
891 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000892#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000893 std = Py_None;
894 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000895#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000896 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000897#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000898 }
899 else {
900 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
901 if (std == NULL)
902 goto error;
903 } /* if (fd < 0) */
904 PySys_SetObject("__stdin__", std);
905 PySys_SetObject("stdin", std);
906 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000907
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000908 /* Set sys.stdout */
909 fd = fileno(stdout);
910 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000911#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000912 std = Py_None;
913 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000914#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000915 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000916#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000917 }
918 else {
919 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
920 if (std == NULL)
921 goto error;
922 } /* if (fd < 0) */
923 PySys_SetObject("__stdout__", std);
924 PySys_SetObject("stdout", std);
925 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000926
Guido van Rossum98297ee2007-11-06 21:34:58 +0000927#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000928 /* Set sys.stderr, replaces the preliminary stderr */
929 fd = fileno(stderr);
930 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000931#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000932 std = Py_None;
933 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000934#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000935 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000936#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000937 }
938 else {
939 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
940 if (std == NULL)
941 goto error;
942 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000943
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000944 /* Same as hack above, pre-import stderr's codec to avoid recursion
945 when import.c tries to write to stderr in verbose mode. */
946 encoding_attr = PyObject_GetAttrString(std, "encoding");
947 if (encoding_attr != NULL) {
948 const char * encoding;
949 encoding = _PyUnicode_AsString(encoding_attr);
950 if (encoding != NULL) {
951 _PyCodec_Lookup(encoding);
952 }
Hirokazu Yamamoto3d897512010-10-30 15:43:30 +0000953 Py_DECREF(encoding_attr);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000954 }
955 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000956
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000957 PySys_SetObject("__stderr__", std);
958 PySys_SetObject("stderr", std);
959 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000960#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000961
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000962 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000963 error:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000964 status = -1;
965 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000966
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000967 if (encoding)
968 free(encoding);
969 Py_XDECREF(bimod);
970 Py_XDECREF(iomod);
971 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000972}
973
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000974/* Parse input from a file and execute it */
975
976int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000977PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000978 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000979{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000980 if (filename == NULL)
981 filename = "???";
982 if (Py_FdIsInteractive(fp, filename)) {
983 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
984 if (closeit)
985 fclose(fp);
986 return err;
987 }
988 else
989 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000990}
991
992int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000993PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000994{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000995 PyObject *v;
996 int ret;
997 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000998
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +0000999 if (flags == NULL) {
1000 flags = &local_flags;
1001 local_flags.cf_flags = 0;
1002 }
1003 v = PySys_GetObject("ps1");
1004 if (v == NULL) {
1005 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1006 Py_XDECREF(v);
1007 }
1008 v = PySys_GetObject("ps2");
1009 if (v == NULL) {
1010 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1011 Py_XDECREF(v);
1012 }
1013 for (;;) {
1014 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1015 PRINT_TOTAL_REFS();
1016 if (ret == E_EOF)
1017 return 0;
1018 /*
1019 if (ret == E_NOMEM)
1020 return -1;
1021 */
1022 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001023}
1024
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001025/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001026static int PARSER_FLAGS(PyCompilerFlags *flags)
1027{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001028 int parser_flags = 0;
1029 if (!flags)
1030 return 0;
1031 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1032 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1033 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1034 parser_flags |= PyPARSE_IGNORE_COOKIE;
1035 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1036 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1037 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001038}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001039
Thomas Wouters89f507f2006-12-13 04:49:30 +00001040#if 0
1041/* Keep an example of flags with future keyword support. */
1042#define PARSER_FLAGS(flags) \
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001043 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1044 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1045 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1046 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001047#endif
1048
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001049int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001050PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001051{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001052 PyObject *m, *d, *v, *w, *oenc = NULL;
1053 mod_ty mod;
1054 PyArena *arena;
1055 char *ps1 = "", *ps2 = "", *enc = NULL;
1056 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001057
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001058 if (fp == stdin) {
1059 /* Fetch encoding from sys.stdin */
1060 v = PySys_GetObject("stdin");
1061 if (v == NULL || v == Py_None)
1062 return -1;
1063 oenc = PyObject_GetAttrString(v, "encoding");
1064 if (!oenc)
1065 return -1;
1066 enc = _PyUnicode_AsString(oenc);
1067 }
1068 v = PySys_GetObject("ps1");
1069 if (v != NULL) {
1070 v = PyObject_Str(v);
1071 if (v == NULL)
1072 PyErr_Clear();
1073 else if (PyUnicode_Check(v))
1074 ps1 = _PyUnicode_AsString(v);
1075 }
1076 w = PySys_GetObject("ps2");
1077 if (w != NULL) {
1078 w = PyObject_Str(w);
1079 if (w == NULL)
1080 PyErr_Clear();
1081 else if (PyUnicode_Check(w))
1082 ps2 = _PyUnicode_AsString(w);
1083 }
1084 arena = PyArena_New();
1085 if (arena == NULL) {
1086 Py_XDECREF(v);
1087 Py_XDECREF(w);
1088 Py_XDECREF(oenc);
1089 return -1;
1090 }
1091 mod = PyParser_ASTFromFile(fp, filename, enc,
1092 Py_single_input, ps1, ps2,
1093 flags, &errcode, arena);
1094 Py_XDECREF(v);
1095 Py_XDECREF(w);
1096 Py_XDECREF(oenc);
1097 if (mod == NULL) {
1098 PyArena_Free(arena);
1099 if (errcode == E_EOF) {
1100 PyErr_Clear();
1101 return E_EOF;
1102 }
1103 PyErr_Print();
1104 return -1;
1105 }
1106 m = PyImport_AddModule("__main__");
1107 if (m == NULL) {
1108 PyArena_Free(arena);
1109 return -1;
1110 }
1111 d = PyModule_GetDict(m);
1112 v = run_mod(mod, filename, d, d, flags, arena);
1113 PyArena_Free(arena);
1114 flush_io();
1115 if (v == NULL) {
1116 PyErr_Print();
1117 return -1;
1118 }
1119 Py_DECREF(v);
1120 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001121}
1122
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001123/* Check whether a file maybe a pyc file: Look at the extension,
1124 the file type, and, if we may close it, at the first few bytes. */
1125
1126static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001127maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001128{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001129 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1130 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001131
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001132 /* Only look into the file if we are allowed to close it, since
1133 it then should also be seekable. */
1134 if (closeit) {
1135 /* Read only two bytes of the magic. If the file was opened in
1136 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1137 be read as they are on disk. */
1138 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1139 unsigned char buf[2];
1140 /* Mess: In case of -x, the stream is NOT at its start now,
1141 and ungetc() was used to push back the first newline,
1142 which makes the current stream position formally undefined,
1143 and a x-platform nightmare.
1144 Unfortunately, we have no direct way to know whether -x
1145 was specified. So we use a terrible hack: if the current
1146 stream position is not 0, we assume -x was specified, and
1147 give up. Bug 132850 on SourceForge spells out the
1148 hopelessness of trying anything else (fseek and ftell
1149 don't work predictably x-platform for text-mode files).
1150 */
1151 int ispyc = 0;
1152 if (ftell(fp) == 0) {
1153 if (fread(buf, 1, 2, fp) == 2 &&
1154 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1155 ispyc = 1;
1156 rewind(fp);
1157 }
1158 return ispyc;
1159 }
1160 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001161}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001162
Guido van Rossum0df002c2000-08-27 19:21:52 +00001163int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001164PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001165 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001166{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001167 PyObject *m, *d, *v;
1168 const char *ext;
1169 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001170
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001171 m = PyImport_AddModule("__main__");
1172 if (m == NULL)
1173 return -1;
1174 d = PyModule_GetDict(m);
1175 if (PyDict_GetItemString(d, "__file__") == NULL) {
1176 PyObject *f;
Victor Stinner15244f72010-10-19 01:22:07 +00001177 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001178 if (f == NULL)
1179 return -1;
1180 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1181 Py_DECREF(f);
1182 return -1;
1183 }
1184 set_file_name = 1;
1185 Py_DECREF(f);
1186 }
1187 len = strlen(filename);
1188 ext = filename + len - (len > 4 ? 4 : 0);
1189 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1190 /* Try to run a pyc file. First, re-open in binary */
1191 if (closeit)
1192 fclose(fp);
1193 if ((fp = fopen(filename, "rb")) == NULL) {
1194 fprintf(stderr, "python: Can't reopen .pyc file\n");
1195 ret = -1;
1196 goto done;
1197 }
1198 /* Turn on optimization if a .pyo file is given */
1199 if (strcmp(ext, ".pyo") == 0)
1200 Py_OptimizeFlag = 1;
1201 v = run_pyc_file(fp, filename, d, d, flags);
1202 } else {
1203 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1204 closeit, flags);
1205 }
1206 flush_io();
1207 if (v == NULL) {
1208 PyErr_Print();
1209 ret = -1;
1210 goto done;
1211 }
1212 Py_DECREF(v);
1213 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001214 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001215 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1216 PyErr_Clear();
1217 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001218}
1219
1220int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001221PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001222{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001223 PyObject *m, *d, *v;
1224 m = PyImport_AddModule("__main__");
1225 if (m == NULL)
1226 return -1;
1227 d = PyModule_GetDict(m);
1228 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1229 if (v == NULL) {
1230 PyErr_Print();
1231 return -1;
1232 }
1233 Py_DECREF(v);
1234 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001235}
1236
Barry Warsaw035574d1997-08-29 22:07:17 +00001237static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001238parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001239 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001240{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001241 long hold;
1242 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001243
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001244 /* old style errors */
1245 if (PyTuple_Check(err))
1246 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1247 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001248
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001249 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001250
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001251 if (! (v = PyObject_GetAttrString(err, "msg")))
1252 goto finally;
1253 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001254
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001255 if (!(v = PyObject_GetAttrString(err, "filename")))
1256 goto finally;
1257 if (v == Py_None)
1258 *filename = NULL;
1259 else if (! (*filename = _PyUnicode_AsString(v)))
1260 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001261
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001262 Py_DECREF(v);
1263 if (!(v = PyObject_GetAttrString(err, "lineno")))
1264 goto finally;
1265 hold = PyLong_AsLong(v);
1266 Py_DECREF(v);
1267 v = NULL;
1268 if (hold < 0 && PyErr_Occurred())
1269 goto finally;
1270 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001271
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001272 if (!(v = PyObject_GetAttrString(err, "offset")))
1273 goto finally;
1274 if (v == Py_None) {
1275 *offset = -1;
1276 Py_DECREF(v);
1277 v = NULL;
1278 } else {
1279 hold = PyLong_AsLong(v);
1280 Py_DECREF(v);
1281 v = NULL;
1282 if (hold < 0 && PyErr_Occurred())
1283 goto finally;
1284 *offset = (int)hold;
1285 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001286
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001287 if (!(v = PyObject_GetAttrString(err, "text")))
1288 goto finally;
1289 if (v == Py_None)
1290 *text = NULL;
1291 else if (!PyUnicode_Check(v) ||
1292 !(*text = _PyUnicode_AsString(v)))
1293 goto finally;
1294 Py_DECREF(v);
1295 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001296
1297finally:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001298 Py_XDECREF(v);
1299 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001300}
1301
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001302void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001303PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001304{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001305 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001306}
1307
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001308static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001309print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001310{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001311 char *nl;
1312 if (offset >= 0) {
Benjamin Petersonc8850d02010-10-29 04:02:30 +00001313 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1314 offset--;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001315 for (;;) {
1316 nl = strchr(text, '\n');
1317 if (nl == NULL || nl-text >= offset)
1318 break;
1319 offset -= (int)(nl+1-text);
1320 text = nl+1;
1321 }
1322 while (*text == ' ' || *text == '\t') {
1323 text++;
1324 offset--;
1325 }
1326 }
1327 PyFile_WriteString(" ", f);
1328 PyFile_WriteString(text, f);
1329 if (*text == '\0' || text[strlen(text)-1] != '\n')
1330 PyFile_WriteString("\n", f);
1331 if (offset == -1)
1332 return;
1333 PyFile_WriteString(" ", f);
Benjamin Petersonc8850d02010-10-29 04:02:30 +00001334 while (--offset > 0)
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001335 PyFile_WriteString(" ", f);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001336 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001337}
1338
Guido van Rossum66e8e862001-03-23 17:54:43 +00001339static void
1340handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001341{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001342 PyObject *exception, *value, *tb;
1343 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001344
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001345 if (Py_InspectFlag)
1346 /* Don't exit if -i flag was given. This flag is set to 0
1347 * when entering interactive mode for inspecting. */
1348 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001349
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001350 PyErr_Fetch(&exception, &value, &tb);
1351 fflush(stdout);
1352 if (value == NULL || value == Py_None)
1353 goto done;
1354 if (PyExceptionInstance_Check(value)) {
1355 /* The error code should be in the `code' attribute. */
1356 PyObject *code = PyObject_GetAttrString(value, "code");
1357 if (code) {
1358 Py_DECREF(value);
1359 value = code;
1360 if (value == Py_None)
1361 goto done;
1362 }
1363 /* If we failed to dig out the 'code' attribute,
1364 just let the else clause below print the error. */
1365 }
1366 if (PyLong_Check(value))
1367 exitcode = (int)PyLong_AsLong(value);
1368 else {
Victor Stinner2e71d012010-05-17 09:35:44 +00001369 PyObject *sys_stderr = PySys_GetObject("stderr");
1370 if (sys_stderr != NULL)
1371 PyObject_CallMethod(sys_stderr, "flush", NULL);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001372 PyObject_Print(value, stderr, Py_PRINT_RAW);
Victor Stinner2e71d012010-05-17 09:35:44 +00001373 fflush(stderr);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001374 PySys_WriteStderr("\n");
1375 exitcode = 1;
1376 }
Tim Peterscf615b52003-04-19 18:47:02 +00001377 done:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001378 /* Restore and clear the exception info, in order to properly decref
1379 * the exception, value, and traceback. If we just exit instead,
1380 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1381 * some finalizers from running.
1382 */
1383 PyErr_Restore(exception, value, tb);
1384 PyErr_Clear();
1385 Py_Exit(exitcode);
1386 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001387}
1388
1389void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001390PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001391{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001392 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001393
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001394 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1395 handle_system_exit();
1396 }
1397 PyErr_Fetch(&exception, &v, &tb);
1398 if (exception == NULL)
1399 return;
1400 PyErr_NormalizeException(&exception, &v, &tb);
1401 if (tb == NULL) {
1402 tb = Py_None;
1403 Py_INCREF(tb);
1404 }
1405 PyException_SetTraceback(v, tb);
1406 if (exception == NULL)
1407 return;
1408 /* Now we know v != NULL too */
1409 if (set_sys_last_vars) {
1410 PySys_SetObject("last_type", exception);
1411 PySys_SetObject("last_value", v);
1412 PySys_SetObject("last_traceback", tb);
1413 }
1414 hook = PySys_GetObject("excepthook");
1415 if (hook) {
1416 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1417 PyObject *result = PyEval_CallObject(hook, args);
1418 if (result == NULL) {
1419 PyObject *exception2, *v2, *tb2;
1420 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1421 handle_system_exit();
1422 }
1423 PyErr_Fetch(&exception2, &v2, &tb2);
1424 PyErr_NormalizeException(&exception2, &v2, &tb2);
1425 /* It should not be possible for exception2 or v2
1426 to be NULL. However PyErr_Display() can't
1427 tolerate NULLs, so just be safe. */
1428 if (exception2 == NULL) {
1429 exception2 = Py_None;
1430 Py_INCREF(exception2);
1431 }
1432 if (v2 == NULL) {
1433 v2 = Py_None;
1434 Py_INCREF(v2);
1435 }
1436 fflush(stdout);
1437 PySys_WriteStderr("Error in sys.excepthook:\n");
1438 PyErr_Display(exception2, v2, tb2);
1439 PySys_WriteStderr("\nOriginal exception was:\n");
1440 PyErr_Display(exception, v, tb);
1441 Py_DECREF(exception2);
1442 Py_DECREF(v2);
1443 Py_XDECREF(tb2);
1444 }
1445 Py_XDECREF(result);
1446 Py_XDECREF(args);
1447 } else {
1448 PySys_WriteStderr("sys.excepthook is missing\n");
1449 PyErr_Display(exception, v, tb);
1450 }
1451 Py_XDECREF(exception);
1452 Py_XDECREF(v);
1453 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001454}
1455
Benjamin Petersone6528212008-07-15 15:32:09 +00001456static void
1457print_exception(PyObject *f, PyObject *value)
1458{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001459 int err = 0;
1460 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001461
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001462 if (!PyExceptionInstance_Check(value)) {
1463 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1464 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1465 PyFile_WriteString(" found\n", f);
1466 return;
1467 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001468
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001469 Py_INCREF(value);
1470 fflush(stdout);
1471 type = (PyObject *) Py_TYPE(value);
1472 tb = PyException_GetTraceback(value);
1473 if (tb && tb != Py_None)
1474 err = PyTraceBack_Print(tb, f);
1475 if (err == 0 &&
1476 PyObject_HasAttrString(value, "print_file_and_line"))
1477 {
1478 PyObject *message;
1479 const char *filename, *text;
1480 int lineno, offset;
1481 if (!parse_syntax_error(value, &message, &filename,
1482 &lineno, &offset, &text))
1483 PyErr_Clear();
1484 else {
1485 char buf[10];
1486 PyFile_WriteString(" File \"", f);
1487 if (filename == NULL)
1488 PyFile_WriteString("<string>", f);
1489 else
1490 PyFile_WriteString(filename, f);
1491 PyFile_WriteString("\", line ", f);
1492 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1493 PyFile_WriteString(buf, f);
1494 PyFile_WriteString("\n", f);
1495 if (text != NULL)
1496 print_error_text(f, offset, text);
1497 Py_DECREF(value);
1498 value = message;
1499 /* Can't be bothered to check all those
1500 PyFile_WriteString() calls */
1501 if (PyErr_Occurred())
1502 err = -1;
1503 }
1504 }
1505 if (err) {
1506 /* Don't do anything else */
1507 }
1508 else {
1509 PyObject* moduleName;
1510 char* className;
1511 assert(PyExceptionClass_Check(type));
1512 className = PyExceptionClass_Name(type);
1513 if (className != NULL) {
1514 char *dot = strrchr(className, '.');
1515 if (dot != NULL)
1516 className = dot+1;
1517 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001518
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001519 moduleName = PyObject_GetAttrString(type, "__module__");
1520 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1521 {
1522 Py_DECREF(moduleName);
1523 err = PyFile_WriteString("<unknown>", f);
1524 }
1525 else {
1526 char* modstr = _PyUnicode_AsString(moduleName);
1527 if (modstr && strcmp(modstr, "builtins"))
1528 {
1529 err = PyFile_WriteString(modstr, f);
1530 err += PyFile_WriteString(".", f);
1531 }
1532 Py_DECREF(moduleName);
1533 }
1534 if (err == 0) {
1535 if (className == NULL)
1536 err = PyFile_WriteString("<unknown>", f);
1537 else
1538 err = PyFile_WriteString(className, f);
1539 }
1540 }
1541 if (err == 0 && (value != Py_None)) {
1542 PyObject *s = PyObject_Str(value);
1543 /* only print colon if the str() of the
1544 object is not the empty string
1545 */
1546 if (s == NULL)
1547 err = -1;
1548 else if (!PyUnicode_Check(s) ||
1549 PyUnicode_GetSize(s) != 0)
1550 err = PyFile_WriteString(": ", f);
1551 if (err == 0)
1552 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1553 Py_XDECREF(s);
1554 }
1555 /* try to write a newline in any case */
1556 err += PyFile_WriteString("\n", f);
1557 Py_XDECREF(tb);
1558 Py_DECREF(value);
1559 /* If an error happened here, don't show it.
1560 XXX This is wrong, but too many callers rely on this behavior. */
1561 if (err != 0)
1562 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001563}
1564
1565static const char *cause_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001566 "\nThe above exception was the direct cause "
1567 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001568
1569static const char *context_message =
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001570 "\nDuring handling of the above exception, "
1571 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001572
1573static void
1574print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1575{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001576 int err = 0, res;
1577 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001578
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001579 if (seen != NULL) {
1580 /* Exception chaining */
1581 if (PySet_Add(seen, value) == -1)
1582 PyErr_Clear();
1583 else if (PyExceptionInstance_Check(value)) {
1584 cause = PyException_GetCause(value);
1585 context = PyException_GetContext(value);
1586 if (cause) {
1587 res = PySet_Contains(seen, cause);
1588 if (res == -1)
1589 PyErr_Clear();
1590 if (res == 0) {
1591 print_exception_recursive(
1592 f, cause, seen);
1593 err |= PyFile_WriteString(
1594 cause_message, f);
1595 }
1596 }
1597 else if (context) {
1598 res = PySet_Contains(seen, context);
1599 if (res == -1)
1600 PyErr_Clear();
1601 if (res == 0) {
1602 print_exception_recursive(
1603 f, context, seen);
1604 err |= PyFile_WriteString(
1605 context_message, f);
1606 }
1607 }
1608 Py_XDECREF(context);
1609 Py_XDECREF(cause);
1610 }
1611 }
1612 print_exception(f, value);
1613 if (err != 0)
1614 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001615}
1616
Thomas Wouters477c8d52006-05-27 19:21:47 +00001617void
1618PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001619{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001620 PyObject *seen;
1621 PyObject *f = PySys_GetObject("stderr");
1622 if (f == Py_None) {
1623 /* pass */
1624 }
1625 else if (f == NULL) {
1626 _PyObject_Dump(value);
1627 fprintf(stderr, "lost sys.stderr\n");
1628 }
1629 else {
1630 /* We choose to ignore seen being possibly NULL, and report
1631 at least the main exception (it could be a MemoryError).
1632 */
1633 seen = PySet_New(NULL);
1634 if (seen == NULL)
1635 PyErr_Clear();
1636 print_exception_recursive(f, value, seen);
1637 Py_XDECREF(seen);
1638 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001639}
1640
Guido van Rossum82598051997-03-05 00:20:32 +00001641PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001642PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001643 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001644{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001645 PyObject *ret = NULL;
1646 mod_ty mod;
1647 PyArena *arena = PyArena_New();
1648 if (arena == NULL)
1649 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001650
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001651 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1652 if (mod != NULL)
1653 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1654 PyArena_Free(arena);
1655 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001656}
1657
1658PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001659PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001660 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001661{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001662 PyObject *ret;
1663 mod_ty mod;
1664 PyArena *arena = PyArena_New();
1665 if (arena == NULL)
1666 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001667
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001668 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1669 flags, NULL, arena);
1670 if (closeit)
1671 fclose(fp);
1672 if (mod == NULL) {
1673 PyArena_Free(arena);
1674 return NULL;
1675 }
1676 ret = run_mod(mod, filename, globals, locals, flags, arena);
1677 PyArena_Free(arena);
1678 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001679}
1680
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001681static void
1682flush_io(void)
1683{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001684 PyObject *f, *r;
1685 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001686
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001687 /* Save the current exception */
1688 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001689
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001690 f = PySys_GetObject("stderr");
1691 if (f != NULL) {
1692 r = PyObject_CallMethod(f, "flush", "");
1693 if (r)
1694 Py_DECREF(r);
1695 else
1696 PyErr_Clear();
1697 }
1698 f = PySys_GetObject("stdout");
1699 if (f != NULL) {
1700 r = PyObject_CallMethod(f, "flush", "");
1701 if (r)
1702 Py_DECREF(r);
1703 else
1704 PyErr_Clear();
1705 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001706
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001707 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001708}
1709
Guido van Rossum82598051997-03-05 00:20:32 +00001710static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001711run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001712 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001713{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001714 PyCodeObject *co;
1715 PyObject *v;
1716 co = PyAST_Compile(mod, filename, flags, arena);
1717 if (co == NULL)
1718 return NULL;
1719 v = PyEval_EvalCode(co, globals, locals);
1720 Py_DECREF(co);
1721 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001722}
1723
Guido van Rossum82598051997-03-05 00:20:32 +00001724static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001725run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001726 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001727{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001728 PyCodeObject *co;
1729 PyObject *v;
1730 long magic;
1731 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001732
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001733 magic = PyMarshal_ReadLongFromFile(fp);
1734 if (magic != PyImport_GetMagicNumber()) {
1735 PyErr_SetString(PyExc_RuntimeError,
1736 "Bad magic number in .pyc file");
1737 return NULL;
1738 }
1739 (void) PyMarshal_ReadLongFromFile(fp);
1740 v = PyMarshal_ReadLastObjectFromFile(fp);
1741 fclose(fp);
1742 if (v == NULL || !PyCode_Check(v)) {
1743 Py_XDECREF(v);
1744 PyErr_SetString(PyExc_RuntimeError,
1745 "Bad code object in .pyc file");
1746 return NULL;
1747 }
1748 co = (PyCodeObject *)v;
1749 v = PyEval_EvalCode(co, globals, locals);
1750 if (v && flags)
1751 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1752 Py_DECREF(co);
1753 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001754}
1755
Guido van Rossum82598051997-03-05 00:20:32 +00001756PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001757Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001758 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001759{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001760 PyCodeObject *co;
1761 mod_ty mod;
1762 PyArena *arena = PyArena_New();
1763 if (arena == NULL)
1764 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001765
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001766 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1767 if (mod == NULL) {
1768 PyArena_Free(arena);
1769 return NULL;
1770 }
1771 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1772 PyObject *result = PyAST_mod2obj(mod);
1773 PyArena_Free(arena);
1774 return result;
1775 }
1776 co = PyAST_Compile(mod, filename, flags, arena);
1777 PyArena_Free(arena);
1778 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001779}
1780
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001781struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001782Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001783{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001784 struct symtable *st;
1785 mod_ty mod;
1786 PyCompilerFlags flags;
1787 PyArena *arena = PyArena_New();
1788 if (arena == NULL)
1789 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001790
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001791 flags.cf_flags = 0;
1792 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1793 if (mod == NULL) {
1794 PyArena_Free(arena);
1795 return NULL;
1796 }
1797 st = PySymtable_Build(mod, filename, 0);
1798 PyArena_Free(arena);
1799 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001800}
1801
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001802/* Preferred access to parser is through AST. */
1803mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001804PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001805 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001806{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001807 mod_ty mod;
1808 PyCompilerFlags localflags;
1809 perrdetail err;
1810 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001811
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001812 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1813 &_PyParser_Grammar, start, &err,
1814 &iflags);
1815 if (flags == NULL) {
1816 localflags.cf_flags = 0;
1817 flags = &localflags;
1818 }
1819 if (n) {
1820 flags->cf_flags |= iflags & PyCF_MASK;
1821 mod = PyAST_FromNode(n, flags, filename, arena);
1822 PyNode_Free(n);
1823 return mod;
1824 }
1825 else {
1826 err_input(&err);
1827 return NULL;
1828 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829}
1830
1831mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001832PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001833 int start, char *ps1,
1834 char *ps2, PyCompilerFlags *flags, int *errcode,
1835 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001836{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001837 mod_ty mod;
1838 PyCompilerFlags localflags;
1839 perrdetail err;
1840 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001841
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001842 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1843 &_PyParser_Grammar,
1844 start, ps1, ps2, &err, &iflags);
1845 if (flags == NULL) {
1846 localflags.cf_flags = 0;
1847 flags = &localflags;
1848 }
1849 if (n) {
1850 flags->cf_flags |= iflags & PyCF_MASK;
1851 mod = PyAST_FromNode(n, flags, filename, arena);
1852 PyNode_Free(n);
1853 return mod;
1854 }
1855 else {
1856 err_input(&err);
1857 if (errcode)
1858 *errcode = err.error;
1859 return NULL;
1860 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861}
1862
Guido van Rossuma110aa61994-08-29 12:50:44 +00001863/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001864
Guido van Rossuma110aa61994-08-29 12:50:44 +00001865node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001866PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001867{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001868 perrdetail err;
1869 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1870 &_PyParser_Grammar,
1871 start, NULL, NULL, &err, flags);
1872 if (n == NULL)
1873 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001874
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001875 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001876}
1877
Guido van Rossuma110aa61994-08-29 12:50:44 +00001878/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001879
Guido van Rossuma110aa61994-08-29 12:50:44 +00001880node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001881PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001882{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001883 perrdetail err;
1884 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1885 start, &err, flags);
1886 if (n == NULL)
1887 err_input(&err);
1888 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001889}
1890
1891node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001892PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001893 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001894{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001895 perrdetail err;
1896 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1897 &_PyParser_Grammar, start, &err, flags);
1898 if (n == NULL)
1899 err_input(&err);
1900 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001901}
1902
1903node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001904PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001905{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001906 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001907}
1908
Guido van Rossum66ebd912003-04-17 16:02:26 +00001909/* May want to move a more generalized form of this to parsetok.c or
1910 even parser modules. */
1911
1912void
1913PyParser_SetError(perrdetail *err)
1914{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001915 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001916}
1917
Guido van Rossuma110aa61994-08-29 12:50:44 +00001918/* Set the error appropriate to the given input error code (see errcode.h) */
1919
1920static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001921err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001922{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001923 PyObject *v, *w, *errtype, *errtext;
1924 PyObject* u = NULL;
Victor Stinner15244f72010-10-19 01:22:07 +00001925 PyObject *filename;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001926 char *msg = NULL;
Victor Stinner15244f72010-10-19 01:22:07 +00001927
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001928 errtype = PyExc_SyntaxError;
1929 switch (err->error) {
1930 case E_ERROR:
1931 return;
1932 case E_SYNTAX:
1933 errtype = PyExc_IndentationError;
1934 if (err->expected == INDENT)
1935 msg = "expected an indented block";
1936 else if (err->token == INDENT)
1937 msg = "unexpected indent";
1938 else if (err->token == DEDENT)
1939 msg = "unexpected unindent";
1940 else {
1941 errtype = PyExc_SyntaxError;
1942 msg = "invalid syntax";
1943 }
1944 break;
1945 case E_TOKEN:
1946 msg = "invalid token";
1947 break;
1948 case E_EOFS:
1949 msg = "EOF while scanning triple-quoted string literal";
1950 break;
1951 case E_EOLS:
1952 msg = "EOL while scanning string literal";
1953 break;
1954 case E_INTR:
1955 if (!PyErr_Occurred())
1956 PyErr_SetNone(PyExc_KeyboardInterrupt);
1957 goto cleanup;
1958 case E_NOMEM:
1959 PyErr_NoMemory();
1960 goto cleanup;
1961 case E_EOF:
1962 msg = "unexpected EOF while parsing";
1963 break;
1964 case E_TABSPACE:
1965 errtype = PyExc_TabError;
1966 msg = "inconsistent use of tabs and spaces in indentation";
1967 break;
1968 case E_OVERFLOW:
1969 msg = "expression too long";
1970 break;
1971 case E_DEDENT:
1972 errtype = PyExc_IndentationError;
1973 msg = "unindent does not match any outer indentation level";
1974 break;
1975 case E_TOODEEP:
1976 errtype = PyExc_IndentationError;
1977 msg = "too many levels of indentation";
1978 break;
1979 case E_DECODE: {
1980 PyObject *type, *value, *tb;
1981 PyErr_Fetch(&type, &value, &tb);
1982 if (value != NULL) {
1983 u = PyObject_Str(value);
1984 if (u != NULL) {
1985 msg = _PyUnicode_AsString(u);
1986 }
1987 }
1988 if (msg == NULL)
1989 msg = "unknown decode error";
1990 Py_XDECREF(type);
1991 Py_XDECREF(value);
1992 Py_XDECREF(tb);
1993 break;
1994 }
1995 case E_LINECONT:
1996 msg = "unexpected character after line continuation character";
1997 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001998
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00001999 case E_IDENTIFIER:
2000 msg = "invalid character in identifier";
2001 break;
2002 default:
2003 fprintf(stderr, "error=%d\n", err->error);
2004 msg = "unknown parsing error";
2005 break;
2006 }
2007 /* err->text may not be UTF-8 in case of decoding errors.
2008 Explicitly convert to an object. */
2009 if (!err->text) {
2010 errtext = Py_None;
2011 Py_INCREF(Py_None);
2012 } else {
2013 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2014 "replace");
2015 }
Victor Stinner15244f72010-10-19 01:22:07 +00002016 if (err->filename != NULL)
2017 filename = PyUnicode_DecodeFSDefault(err->filename);
2018 else {
2019 Py_INCREF(Py_None);
2020 filename = Py_None;
2021 }
2022 if (filename != NULL)
2023 v = Py_BuildValue("(NiiN)", filename,
2024 err->lineno, err->offset, errtext);
2025 else
2026 v = NULL;
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002027 w = NULL;
2028 if (v != NULL)
2029 w = Py_BuildValue("(sO)", msg, v);
2030 Py_XDECREF(u);
2031 Py_XDECREF(v);
2032 PyErr_SetObject(errtype, w);
2033 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002034cleanup:
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002035 if (err->text != NULL) {
2036 PyObject_FREE(err->text);
2037 err->text = NULL;
2038 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002039}
2040
2041/* Print fatal error message and abort */
2042
2043void
Tim Peters7c321a82002-07-09 02:57:01 +00002044Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002045{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002046 fprintf(stderr, "Fatal Python error: %s\n", msg);
2047 fflush(stderr); /* it helps in Windows debug build */
2048 if (PyErr_Occurred()) {
Victor Stinner93362d42010-06-08 21:05:20 +00002049 PyErr_PrintEx(0);
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002050 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002051#ifdef MS_WINDOWS
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002052 {
2053 size_t len = strlen(msg);
2054 WCHAR* buffer;
2055 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002056
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002057 /* Convert the message to wchar_t. This uses a simple one-to-one
2058 conversion, assuming that the this error message actually uses ASCII
2059 only. If this ceases to be true, we will have to convert. */
2060 buffer = alloca( (len+1) * (sizeof *buffer));
2061 for( i=0; i<=len; ++i)
2062 buffer[i] = msg[i];
2063 OutputDebugStringW(L"Fatal Python error: ");
2064 OutputDebugStringW(buffer);
2065 OutputDebugStringW(L"\n");
2066 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002067#ifdef _DEBUG
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002068 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002069#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002070#endif /* MS_WINDOWS */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002071 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002072}
2073
2074/* Clean up and exit */
2075
Guido van Rossuma110aa61994-08-29 12:50:44 +00002076#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002077#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002078#endif
2079
Collin Winter670e6922007-03-21 02:57:17 +00002080static void (*pyexitfunc)(void) = NULL;
2081/* For the atexit module. */
2082void _Py_PyAtExit(void (*func)(void))
2083{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002084 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002085}
2086
2087static void
2088call_py_exitfuncs(void)
2089{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002090 if (pyexitfunc == NULL)
2091 return;
Collin Winter670e6922007-03-21 02:57:17 +00002092
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002093 (*pyexitfunc)();
2094 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002095}
2096
Antoine Pitroucefb3162009-10-20 22:08:36 +00002097/* Wait until threading._shutdown completes, provided
2098 the threading module was imported in the first place.
2099 The shutdown routine will wait until all non-daemon
2100 "threading" threads have completed. */
2101static void
2102wait_for_thread_shutdown(void)
2103{
2104#ifdef WITH_THREAD
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002105 PyObject *result;
2106 PyThreadState *tstate = PyThreadState_GET();
2107 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2108 "threading");
2109 if (threading == NULL) {
2110 /* threading not imported */
2111 PyErr_Clear();
2112 return;
2113 }
2114 result = PyObject_CallMethod(threading, "_shutdown", "");
2115 if (result == NULL) {
2116 PyErr_WriteUnraisable(threading);
2117 }
2118 else {
2119 Py_DECREF(result);
2120 }
2121 Py_DECREF(threading);
Antoine Pitroucefb3162009-10-20 22:08:36 +00002122#endif
2123}
2124
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002125#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002126static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002127static int nexitfuncs = 0;
2128
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002129int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002130{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002131 if (nexitfuncs >= NEXITFUNCS)
2132 return -1;
2133 exitfuncs[nexitfuncs++] = func;
2134 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002135}
2136
Guido van Rossumcc283f51997-08-05 02:22:03 +00002137static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002138call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002139{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002140 while (nexitfuncs > 0)
2141 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002142
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002143 fflush(stdout);
2144 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002145}
2146
2147void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002148Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002149{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002150 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002151
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002152 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002153}
2154
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002155static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002156initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002157{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002158#ifdef SIGPIPE
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002159 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002160#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002161#ifdef SIGXFZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002162 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002163#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002164#ifdef SIGXFSZ
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002165 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002166#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002167 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002168}
2169
Guido van Rossum7433b121997-02-14 19:45:36 +00002170
2171/*
2172 * The file descriptor fd is considered ``interactive'' if either
2173 * a) isatty(fd) is TRUE, or
2174 * b) the -i flag was given, and the filename associated with
2175 * the descriptor is NULL or "<stdin>" or "???".
2176 */
2177int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002178Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002179{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002180 if (isatty((int)fileno(fp)))
2181 return 1;
2182 if (!Py_InteractiveFlag)
2183 return 0;
2184 return (filename == NULL) ||
2185 (strcmp(filename, "<stdin>") == 0) ||
2186 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002187}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002188
2189
Tim Petersd08e3822003-04-17 15:24:21 +00002190#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002191#if defined(WIN32) && defined(_MSC_VER)
2192
2193/* Stack checking for Microsoft C */
2194
2195#include <malloc.h>
2196#include <excpt.h>
2197
Fred Drakee8de31c2000-08-31 05:38:39 +00002198/*
2199 * Return non-zero when we run out of memory on the stack; zero otherwise.
2200 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002201int
Fred Drake399739f2000-08-31 05:52:44 +00002202PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002203{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002204 __try {
2205 /* alloca throws a stack overflow exception if there's
2206 not enough space left on the stack */
2207 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2208 return 0;
2209 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2210 EXCEPTION_EXECUTE_HANDLER :
2211 EXCEPTION_CONTINUE_SEARCH) {
2212 int errcode = _resetstkoflw();
2213 if (errcode == 0)
2214 {
2215 Py_FatalError("Could not reset the stack!");
2216 }
2217 }
2218 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002219}
2220
2221#endif /* WIN32 && _MSC_VER */
2222
2223/* Alternate implementations can be added here... */
2224
2225#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002226
2227
2228/* Wrappers around sigaction() or signal(). */
2229
2230PyOS_sighandler_t
2231PyOS_getsig(int sig)
2232{
2233#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002234 struct sigaction context;
2235 if (sigaction(sig, NULL, &context) == -1)
2236 return SIG_ERR;
2237 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002238#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002239 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002240/* Special signal handling for the secure CRT in Visual Studio 2005 */
2241#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002242 switch (sig) {
2243 /* Only these signals are valid */
2244 case SIGINT:
2245 case SIGILL:
2246 case SIGFPE:
2247 case SIGSEGV:
2248 case SIGTERM:
2249 case SIGBREAK:
2250 case SIGABRT:
2251 break;
2252 /* Don't call signal() with other values or it will assert */
2253 default:
2254 return SIG_ERR;
2255 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002256#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002257 handler = signal(sig, SIG_IGN);
2258 if (handler != SIG_ERR)
2259 signal(sig, handler);
2260 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002261#endif
2262}
2263
2264PyOS_sighandler_t
2265PyOS_setsig(int sig, PyOS_sighandler_t handler)
2266{
2267#ifdef HAVE_SIGACTION
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002268 /* Some code in Modules/signalmodule.c depends on sigaction() being
2269 * used here if HAVE_SIGACTION is defined. Fix that if this code
2270 * changes to invalidate that assumption.
2271 */
2272 struct sigaction context, ocontext;
2273 context.sa_handler = handler;
2274 sigemptyset(&context.sa_mask);
2275 context.sa_flags = 0;
2276 if (sigaction(sig, &context, &ocontext) == -1)
2277 return SIG_ERR;
2278 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002279#else
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002280 PyOS_sighandler_t oldhandler;
2281 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002282#ifdef HAVE_SIGINTERRUPT
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002283 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002284#endif
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002285 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002286#endif
2287}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288
2289/* Deprecated C API functions still provided for binary compatiblity */
2290
2291#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002292PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002293PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2294{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002295 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002296}
2297
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002298#undef PyParser_SimpleParseString
2299PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002300PyParser_SimpleParseString(const char *str, int start)
2301{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002302 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002304
2305#undef PyRun_AnyFile
2306PyAPI_FUNC(int)
2307PyRun_AnyFile(FILE *fp, const char *name)
2308{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002309 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002310}
2311
2312#undef PyRun_AnyFileEx
2313PyAPI_FUNC(int)
2314PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2315{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002316 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002317}
2318
2319#undef PyRun_AnyFileFlags
2320PyAPI_FUNC(int)
2321PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2322{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002323 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002324}
2325
2326#undef PyRun_File
2327PyAPI_FUNC(PyObject *)
2328PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2329{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002330 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002331}
2332
2333#undef PyRun_FileEx
2334PyAPI_FUNC(PyObject *)
2335PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2336{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002337 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002338}
2339
2340#undef PyRun_FileFlags
2341PyAPI_FUNC(PyObject *)
2342PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002343 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002344{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002345 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002346}
2347
2348#undef PyRun_SimpleFile
2349PyAPI_FUNC(int)
2350PyRun_SimpleFile(FILE *f, const char *p)
2351{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002352 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002353}
2354
2355#undef PyRun_SimpleFileEx
2356PyAPI_FUNC(int)
2357PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2358{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002359 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002360}
2361
2362
2363#undef PyRun_String
2364PyAPI_FUNC(PyObject *)
2365PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2366{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002367 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002368}
2369
2370#undef PyRun_SimpleString
2371PyAPI_FUNC(int)
2372PyRun_SimpleString(const char *s)
2373{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002374 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002375}
2376
2377#undef Py_CompileString
2378PyAPI_FUNC(PyObject *)
2379Py_CompileString(const char *str, const char *p, int s)
2380{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002381 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002382}
2383
2384#undef PyRun_InteractiveOne
2385PyAPI_FUNC(int)
2386PyRun_InteractiveOne(FILE *f, const char *p)
2387{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002388 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002389}
2390
2391#undef PyRun_InteractiveLoop
2392PyAPI_FUNC(int)
2393PyRun_InteractiveLoop(FILE *f, const char *p)
2394{
Antoine Pitrou7f14f0d2010-05-09 16:14:21 +00002395 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002396}
2397
2398#ifdef __cplusplus
2399}
2400#endif