blob: f45d7dc9fa9970db49f4a4244216338de858d8fc [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Antoine Pitrou011bd622009-10-20 21:52:47 +000021#include "abstract.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000022
Thomas Wouters0e3f5912006-08-11 14:57:12 +000023#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000024#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000026
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000027#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000028#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000029#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000030
Martin v. Löwis73d538b2003-03-05 15:13:47 +000031#ifdef HAVE_LANGINFO_H
32#include <locale.h>
33#include <langinfo.h>
34#endif
35
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000036#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000037#undef BYTE
38#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000039#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000040#endif
41
Neal Norwitz4281cef2006-03-04 19:58:13 +000042#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000044#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045#define PRINT_TOTAL_REFS() fprintf(stderr, \
46 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
47 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000048#endif
49
50#ifdef __cplusplus
51extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000052#endif
53
Martin v. Löwis790465f2008-04-05 20:41:37 +000054extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000055
Guido van Rossum82598051997-03-05 00:20:32 +000056extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000057
Guido van Rossumb73cc041993-11-01 16:28:59 +000058/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000059static void initmain(void);
Victor Stinnerb744ba12010-05-15 12:27:16 +000060static void initfsencoding(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000061static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000062static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000063static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000066static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000068static void err_input(perrdetail *);
69static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000070static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000071static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000072static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000073extern void _PyUnicode_Init(void);
74extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000075extern int _PyLong_Init(void);
76extern void PyLong_Fini(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 */
Guido van Rossumd8faa362007-04-27 19:54:29 +000086int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
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} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000095
Christian Heimes33fe8092008-04-13 13:53:33 +000096/* PyModule_GetWarningsModule is no longer necessary as of 2.6
97since _warnings is builtin. This API should not be used. */
98PyObject *
99PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000102}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000103
Guido van Rossum25ce5661997-08-02 03:10:38 +0000104static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000105
Thomas Wouters7e474022000-07-16 12:04:32 +0000106/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000107
108int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000109Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000112}
113
Guido van Rossum25ce5661997-08-02 03:10:38 +0000114/* Global initializations. Can be undone by Py_Finalize(). Don't
115 call this twice without an intervening Py_Finalize() call. When
116 initializations fail, a fatal error is issued and the function does
117 not return. On return, the first thread and interpreter state have
118 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000119
Guido van Rossum25ce5661997-08-02 03:10:38 +0000120 Locking: you must hold the interpreter lock while calling this.
121 (If the lock has not yet been initialized, that's equivalent to
122 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000123
Guido van Rossum25ce5661997-08-02 03:10:38 +0000124*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000125
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000126static int
127add_flag(int flag, const char *envs)
128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int env = atoi(envs);
130 if (flag < env)
131 flag = env;
132 if (flag < 1)
133 flag = 1;
134 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000135}
136
Christian Heimes5833a2f2008-10-30 21:40:04 +0000137#if defined(HAVE_LANGINFO_H) && defined(CODESET)
138static char*
139get_codeset(void)
140{
Victor Stinner386fe712010-05-19 00:34:15 +0000141 char* codeset, *name_str;
142 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 codeset = nl_langinfo(CODESET);
145 if (!codeset || codeset[0] == '\0')
146 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 codec = _PyCodec_Lookup(codeset);
149 if (!codec)
150 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 name = PyObject_GetAttrString(codec, "name");
153 Py_CLEAR(codec);
154 if (!name)
155 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000156
Victor Stinner386fe712010-05-19 00:34:15 +0000157 name_str = _PyUnicode_AsString(name);
158 if (name == NULL)
159 goto error;
160 codeset = strdup(name_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 Py_DECREF(name);
162 return codeset;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000163
164error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000166 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000168}
169#endif
170
Guido van Rossuma027efa1997-05-05 20:56:21 +0000171void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000172Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 PyInterpreterState *interp;
175 PyThreadState *tstate;
176 PyObject *bimod, *sysmod, *pstderr;
177 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 if (initialized)
181 return;
182 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000183
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000184#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 /* Set up the LC_CTYPE locale, so we can obtain
186 the locale's charset without having to switch
187 locales. */
188 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000189#endif
190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
192 Py_DebugFlag = add_flag(Py_DebugFlag, p);
193 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
194 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
195 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
196 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
197 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
198 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 interp = PyInterpreterState_New();
201 if (interp == NULL)
202 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 tstate = PyThreadState_New(interp);
205 if (tstate == NULL)
206 Py_FatalError("Py_Initialize: can't make first thread");
207 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 if (!_PyFrame_Init())
212 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 if (!_PyLong_Init())
215 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 if (!PyByteArray_Init())
218 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 interp->modules = PyDict_New();
223 if (interp->modules == NULL)
224 Py_FatalError("Py_Initialize: can't make modules dictionary");
225 interp->modules_reloading = PyDict_New();
226 if (interp->modules_reloading == NULL)
227 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 /* Init Unicode implementation; relies on the codec registry */
230 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 bimod = _PyBuiltin_Init();
233 if (bimod == NULL)
234 Py_FatalError("Py_Initialize: can't initialize builtins modules");
235 _PyImport_FixupExtension(bimod, "builtins", "builtins");
236 interp->builtins = PyModule_GetDict(bimod);
237 if (interp->builtins == NULL)
238 Py_FatalError("Py_Initialize: can't initialize builtins dict");
239 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 /* initialize builtin exceptions */
242 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 sysmod = _PySys_Init();
245 if (sysmod == NULL)
246 Py_FatalError("Py_Initialize: can't initialize sys");
247 interp->sysdict = PyModule_GetDict(sysmod);
248 if (interp->sysdict == NULL)
249 Py_FatalError("Py_Initialize: can't initialize sys dict");
250 Py_INCREF(interp->sysdict);
251 _PyImport_FixupExtension(sysmod, "sys", "sys");
252 PySys_SetPath(Py_GetPath());
253 PyDict_SetItemString(interp->sysdict, "modules",
254 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 /* Set up a preliminary stderr printer until we have enough
257 infrastructure for the io module in place. */
258 pstderr = PyFile_NewStdPrinter(fileno(stderr));
259 if (pstderr == NULL)
260 Py_FatalError("Py_Initialize: can't set preliminary stderr");
261 PySys_SetObject("stderr", pstderr);
262 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000267
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000268 /* Initialize _warnings. */
269 _PyWarnings_Init();
270
Victor Stinnerb744ba12010-05-15 12:27:16 +0000271 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (install_sigs)
274 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* Initialize warnings. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 if (PySys_HasWarnOptions()) {
278 PyObject *warnings_module = PyImport_ImportModule("warnings");
279 if (!warnings_module)
280 PyErr_Clear();
281 Py_XDECREF(warnings_module);
282 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 initmain(); /* Module __main__ */
285 if (initstdio() < 0)
286 Py_FatalError(
287 "Py_Initialize: can't initialize sys standard streams");
288
289 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000290#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000292#endif /* WITH_THREAD */
Victor Stinner52f6dd72010-03-12 14:45:56 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 if (!Py_NoSiteFlag)
295 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000296}
297
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000298void
299Py_Initialize(void)
300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000302}
303
304
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000305#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000306extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000307#endif
308
Guido van Rossume8432ac2007-07-09 15:04:50 +0000309/* Flush stdout and stderr */
310
Neal Norwitz2bad9702007-08-27 06:19:22 +0000311static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000312flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 PyObject *fout = PySys_GetObject("stdout");
315 PyObject *ferr = PySys_GetObject("stderr");
316 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 if (fout != NULL && fout != Py_None) {
319 tmp = PyObject_CallMethod(fout, "flush", "");
320 if (tmp == NULL)
321 PyErr_Clear();
322 else
323 Py_DECREF(tmp);
324 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000325
Victor Stinner9467b212010-05-14 00:59:09 +0000326 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 tmp = PyObject_CallMethod(ferr, "flush", "");
328 if (tmp == NULL)
329 PyErr_Clear();
330 else
331 Py_DECREF(tmp);
332 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000333}
334
Guido van Rossum25ce5661997-08-02 03:10:38 +0000335/* Undo the effect of Py_Initialize().
336
337 Beware: if multiple interpreter and/or thread states exist, these
338 are not wiped out; only the current thread and interpreter state
339 are deleted. But since everything else is deleted, those other
340 interpreter and thread states should no longer be used.
341
342 (XXX We should do better, e.g. wipe out all interpreters and
343 threads.)
344
345 Locking: as above.
346
347*/
348
349void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000350Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 PyInterpreterState *interp;
353 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (!initialized)
356 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 /* The interpreter is still entirely intact at this point, and the
361 * exit funcs may be relying on that. In particular, if some thread
362 * or exit func is still waiting to do an import, the import machinery
363 * expects Py_IsInitialized() to return true. So don't say the
364 * interpreter is uninitialized until after the exit funcs have run.
365 * Note that Threading.py uses an exit func to do a join on all the
366 * threads created thru it, so this also protects pending imports in
367 * the threads created via Threading.
368 */
369 call_py_exitfuncs();
370 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 /* Flush stdout+stderr */
373 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 /* Get current thread state and interpreter pointer */
376 tstate = PyThreadState_GET();
377 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 /* Disable signal handling */
380 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 /* Clear type lookup cache */
383 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* Collect garbage. This may call finalizers; it's nice to call these
386 * before all modules are destroyed.
387 * XXX If a __del__ or weakref callback is triggered here, and tries to
388 * XXX import a module, bad things can happen, because Python no
389 * XXX longer believes it's initialized.
390 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
391 * XXX is easy to provoke that way. I've also seen, e.g.,
392 * XXX Exception exceptions.ImportError: 'No module named sha'
393 * XXX in <function callback at 0x008F5718> ignored
394 * XXX but I'm unclear on exactly how that one happens. In any case,
395 * XXX I haven't seen a real-life report of either of these.
396 */
397 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000398#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 /* With COUNT_ALLOCS, it helps to run GC multiple times:
400 each collection might release some types from the type
401 list, so they become garbage. */
402 while (PyGC_Collect() > 0)
403 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000404#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 /* Destroy all modules */
407 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 /* Flush stdout+stderr (again, in case more was printed) */
410 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 /* Collect final garbage. This disposes of cycles created by
413 * new-style class definitions, for example.
414 * XXX This is disabled because it caused too many problems. If
415 * XXX a __del__ or weakref callback triggers here, Python code has
416 * XXX a hard time running, because even the sys module has been
417 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
418 * XXX One symptom is a sequence of information-free messages
419 * XXX coming from threads (if a __del__ or callback is invoked,
420 * XXX other threads can execute too, and any exception they encounter
421 * XXX triggers a comedy of errors as subsystem after subsystem
422 * XXX fails to find what it *expects* to find in sys to help report
423 * XXX the exception and consequent unexpected failures). I've also
424 * XXX seen segfaults then, after adding print statements to the
425 * XXX Python code getting called.
426 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000427#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000429#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
432 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000435#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000437#endif
438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000440
Tim Peters9cf25ce2003-04-17 15:21:01 +0000441#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 /* Display all objects still alive -- this can invoke arbitrary
443 * __repr__ overrides, so requires a mostly-intact interpreter.
444 * Alas, a lot of stuff may still be alive now that will be cleaned
445 * up later.
446 */
447 if (Py_GETENV("PYTHONDUMPREFS"))
448 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000449#endif /* Py_TRACE_REFS */
450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 /* Clear interpreter state */
452 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* Now we decref the exception classes. After this point nothing
455 can raise an exception. That's okay, because each Fini() method
456 below has been checked to make sure no exceptions are ever
457 raised.
458 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000463#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000465#endif /* WITH_THREAD */
466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 /* Delete current thread */
468 PyThreadState_Swap(NULL);
469 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 /* Sundry finalizers */
472 PyMethod_Fini();
473 PyFrame_Fini();
474 PyCFunction_Fini();
475 PyTuple_Fini();
476 PyList_Fini();
477 PySet_Fini();
478 PyBytes_Fini();
479 PyByteArray_Fini();
480 PyLong_Fini();
481 PyFloat_Fini();
482 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* Cleanup Unicode implementation */
485 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000488 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 free((char*)Py_FileSystemDefaultEncoding);
490 Py_FileSystemDefaultEncoding = NULL;
491 }
Christian Heimesc8967002007-11-30 10:18:26 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 /* XXX Still allocated:
494 - various static ad-hoc pointers to interned strings
495 - int and float free list blocks
496 - whatever various modules and libraries allocate
497 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000500
Tim Peters269b2a62003-04-17 19:52:29 +0000501#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 /* Display addresses (& refcnts) of all objects still alive.
503 * An address can be used to find the repr of the object, printed
504 * above by _Py_PrintReferences.
505 */
506 if (Py_GETENV("PYTHONDUMPREFS"))
507 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000508#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000509#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (Py_GETENV("PYTHONMALLOCSTATS"))
511 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000512#endif
513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000515}
516
517/* Create and initialize a new interpreter and thread, and return the
518 new thread. This requires that Py_Initialize() has been called
519 first.
520
521 Unsuccessful initialization yields a NULL pointer. Note that *no*
522 exception information is available even in this case -- the
523 exception information is held in the thread, and there is no
524 thread.
525
526 Locking: as above.
527
528*/
529
530PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000531Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 PyInterpreterState *interp;
534 PyThreadState *tstate, *save_tstate;
535 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (!initialized)
538 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 interp = PyInterpreterState_New();
541 if (interp == NULL)
542 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 tstate = PyThreadState_New(interp);
545 if (tstate == NULL) {
546 PyInterpreterState_Delete(interp);
547 return NULL;
548 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 interp->modules = PyDict_New();
555 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 bimod = _PyImport_FindExtension("builtins", "builtins");
558 if (bimod != NULL) {
559 interp->builtins = PyModule_GetDict(bimod);
560 if (interp->builtins == NULL)
561 goto handle_error;
562 Py_INCREF(interp->builtins);
563 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 /* initialize builtin exceptions */
566 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 sysmod = _PyImport_FindExtension("sys", "sys");
569 if (bimod != NULL && sysmod != NULL) {
570 PyObject *pstderr;
571 interp->sysdict = PyModule_GetDict(sysmod);
572 if (interp->sysdict == NULL)
573 goto handle_error;
574 Py_INCREF(interp->sysdict);
575 PySys_SetPath(Py_GetPath());
576 PyDict_SetItemString(interp->sysdict, "modules",
577 interp->modules);
578 /* Set up a preliminary stderr printer until we have enough
579 infrastructure for the io module in place. */
580 pstderr = PyFile_NewStdPrinter(fileno(stderr));
581 if (pstderr == NULL)
582 Py_FatalError("Py_Initialize: can't set preliminary stderr");
583 PySys_SetObject("stderr", pstderr);
584 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 _PyImportHooks_Init();
587 if (initstdio() < 0)
588 Py_FatalError(
589 "Py_Initialize: can't initialize sys standard streams");
590 initmain();
591 if (!Py_NoSiteFlag)
592 initsite();
593 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (!PyErr_Occurred())
596 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000597
Thomas Wouters89f507f2006-12-13 04:49:30 +0000598handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyErr_Print();
602 PyThreadState_Clear(tstate);
603 PyThreadState_Swap(save_tstate);
604 PyThreadState_Delete(tstate);
605 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608}
609
610/* Delete an interpreter and its last thread. This requires that the
611 given thread state is current, that the thread has no remaining
612 frames, and that it is its interpreter's only remaining thread.
613 It is a fatal error to violate these constraints.
614
615 (Py_Finalize() doesn't have these constraints -- it zaps
616 everything, regardless.)
617
618 Locking: as above.
619
620*/
621
622void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000623Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 if (tstate != PyThreadState_GET())
628 Py_FatalError("Py_EndInterpreter: thread is not current");
629 if (tstate->frame != NULL)
630 Py_FatalError("Py_EndInterpreter: thread still has a frame");
631 if (tstate != interp->tstate_head || tstate->next != NULL)
632 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 PyImport_Cleanup();
635 PyInterpreterState_Clear(interp);
636 PyThreadState_Swap(NULL);
637 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000638}
639
Martin v. Löwis790465f2008-04-05 20:41:37 +0000640static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000641
642void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000643Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 if (pn && *pn)
646 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000647}
648
Martin v. Löwis790465f2008-04-05 20:41:37 +0000649wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000650Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000653}
654
Martin v. Löwis790465f2008-04-05 20:41:37 +0000655static wchar_t *default_home = NULL;
656static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000657
658void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000659Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000662}
663
Martin v. Löwis790465f2008-04-05 20:41:37 +0000664wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000665Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 wchar_t *home = default_home;
668 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
669 char* chome = Py_GETENV("PYTHONHOME");
670 if (chome) {
671 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
672 if (r != (size_t)-1 && r <= PATH_MAX)
673 home = env_home;
674 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 }
677 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000678}
679
Guido van Rossum6135a871995-01-09 17:53:26 +0000680/* Create __main__ module */
681
682static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000683initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyObject *m, *d;
686 m = PyImport_AddModule("__main__");
687 if (m == NULL)
688 Py_FatalError("can't create __main__ module");
689 d = PyModule_GetDict(m);
690 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
691 PyObject *bimod = PyImport_ImportModule("builtins");
692 if (bimod == NULL ||
693 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
694 Py_FatalError("can't add __builtins__ to __main__");
695 Py_DECREF(bimod);
696 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000697}
698
Victor Stinnerb744ba12010-05-15 12:27:16 +0000699static void
700initfsencoding(void)
701{
702 PyObject *codec;
703#if defined(HAVE_LANGINFO_H) && defined(CODESET)
704 char *codeset;
705
Victor Stinner7f84ab52010-06-11 00:36:33 +0000706 if (Py_FileSystemDefaultEncoding == NULL) {
707 /* On Unix, set the file system encoding according to the
708 user's preference, if the CODESET names a well-known
709 Python codec, and Py_FileSystemDefaultEncoding isn't
710 initialized by other means. Also set the encoding of
711 stdin and stdout if these are terminals. */
712 codeset = get_codeset();
713 if (codeset != NULL) {
714 Py_FileSystemDefaultEncoding = codeset;
715 Py_HasFileSystemDefaultEncoding = 0;
716 return;
717 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000718
Victor Stinner7f84ab52010-06-11 00:36:33 +0000719 PyErr_Clear();
720 fprintf(stderr,
721 "Unable to get the locale encoding: "
722 "fallback to utf-8\n");
723 Py_FileSystemDefaultEncoding = "utf-8";
724 Py_HasFileSystemDefaultEncoding = 1;
725 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000726#endif
727
728 /* the encoding is mbcs, utf-8 or ascii */
729 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
730 if (!codec) {
731 /* Such error can only occurs in critical situations: no more
732 * memory, import a module of the standard library failed,
733 * etc. */
734 Py_FatalError("Py_Initialize: unable to load the file system codec");
735 } else {
736 Py_DECREF(codec);
737 }
738}
739
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000740/* Import the site module (not into __main__ though) */
741
742static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000743initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 PyObject *m;
746 m = PyImport_ImportModule("site");
747 if (m == NULL) {
748 PyErr_Print();
749 Py_Finalize();
750 exit(1);
751 }
752 else {
753 Py_DECREF(m);
754 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000755}
756
Antoine Pitrou05608432009-01-09 18:53:14 +0000757static PyObject*
758create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 int fd, int write_mode, char* name,
760 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
763 const char* mode;
764 PyObject *line_buffering;
765 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 /* stdin is always opened in buffered mode, first because it shouldn't
768 make a difference in common use cases, second because TextIOWrapper
769 depends on the presence of a read1() method which only exists on
770 buffered streams.
771 */
772 if (Py_UnbufferedStdioFlag && write_mode)
773 buffering = 0;
774 else
775 buffering = -1;
776 if (write_mode)
777 mode = "wb";
778 else
779 mode = "rb";
780 buf = PyObject_CallMethod(io, "open", "isiOOOi",
781 fd, mode, buffering,
782 Py_None, Py_None, Py_None, 0);
783 if (buf == NULL)
784 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (buffering) {
787 raw = PyObject_GetAttrString(buf, "raw");
788 if (raw == NULL)
789 goto error;
790 }
791 else {
792 raw = buf;
793 Py_INCREF(raw);
794 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 text = PyUnicode_FromString(name);
797 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
798 goto error;
799 res = PyObject_CallMethod(raw, "isatty", "");
800 if (res == NULL)
801 goto error;
802 isatty = PyObject_IsTrue(res);
803 Py_DECREF(res);
804 if (isatty == -1)
805 goto error;
806 if (isatty || Py_UnbufferedStdioFlag)
807 line_buffering = Py_True;
808 else
809 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 Py_CLEAR(raw);
812 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
815 buf, encoding, errors,
816 "\n", line_buffering);
817 Py_CLEAR(buf);
818 if (stream == NULL)
819 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (write_mode)
822 mode = "w";
823 else
824 mode = "r";
825 text = PyUnicode_FromString(mode);
826 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
827 goto error;
828 Py_CLEAR(text);
829 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000830
831error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 Py_XDECREF(buf);
833 Py_XDECREF(stream);
834 Py_XDECREF(text);
835 Py_XDECREF(raw);
836 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000837}
838
Georg Brandl1a3284e2007-12-02 09:40:06 +0000839/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000840static int
841initstdio(void)
842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 PyObject *iomod = NULL, *wrapper;
844 PyObject *bimod = NULL;
845 PyObject *m;
846 PyObject *std = NULL;
847 int status = 0, fd;
848 PyObject * encoding_attr;
849 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* Hack to avoid a nasty recursion issue when Python is invoked
852 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
853 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
854 goto error;
855 }
856 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
859 goto error;
860 }
861 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 if (!(bimod = PyImport_ImportModule("builtins"))) {
864 goto error;
865 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if (!(iomod = PyImport_ImportModule("io"))) {
868 goto error;
869 }
870 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
871 goto error;
872 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 /* Set builtins.open */
875 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
876 goto error;
877 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 encoding = Py_GETENV("PYTHONIOENCODING");
880 errors = NULL;
881 if (encoding) {
882 encoding = strdup(encoding);
883 errors = strchr(encoding, ':');
884 if (errors) {
885 *errors = '\0';
886 errors++;
887 }
888 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 /* Set sys.stdin */
891 fd = fileno(stdin);
892 /* Under some conditions stdin, stdout and stderr may not be connected
893 * and fileno() may point to an invalid file descriptor. For example
894 * GUI apps don't have valid standard streams by default.
895 */
896 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000897#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 std = Py_None;
899 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000900#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000902#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 }
904 else {
905 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
906 if (std == NULL)
907 goto error;
908 } /* if (fd < 0) */
909 PySys_SetObject("__stdin__", std);
910 PySys_SetObject("stdin", std);
911 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* Set sys.stdout */
914 fd = fileno(stdout);
915 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000916#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 std = Py_None;
918 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000919#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000921#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 }
923 else {
924 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
925 if (std == NULL)
926 goto error;
927 } /* if (fd < 0) */
928 PySys_SetObject("__stdout__", std);
929 PySys_SetObject("stdout", std);
930 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000931
Guido van Rossum98297ee2007-11-06 21:34:58 +0000932#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Set sys.stderr, replaces the preliminary stderr */
934 fd = fileno(stderr);
935 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000936#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 std = Py_None;
938 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000939#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000941#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 }
943 else {
944 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
945 if (std == NULL)
946 goto error;
947 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* Same as hack above, pre-import stderr's codec to avoid recursion
950 when import.c tries to write to stderr in verbose mode. */
951 encoding_attr = PyObject_GetAttrString(std, "encoding");
952 if (encoding_attr != NULL) {
953 const char * encoding;
954 encoding = _PyUnicode_AsString(encoding_attr);
955 if (encoding != NULL) {
956 _PyCodec_Lookup(encoding);
957 }
958 }
959 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 PySys_SetObject("__stderr__", std);
962 PySys_SetObject("stderr", std);
963 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000964#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000967 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 status = -1;
969 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (encoding)
972 free(encoding);
973 Py_XDECREF(bimod);
974 Py_XDECREF(iomod);
975 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000976}
977
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000978/* Parse input from a file and execute it */
979
980int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000981PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (filename == NULL)
985 filename = "???";
986 if (Py_FdIsInteractive(fp, filename)) {
987 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
988 if (closeit)
989 fclose(fp);
990 return err;
991 }
992 else
993 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000994}
995
996int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000997PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000998{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 PyObject *v;
1000 int ret;
1001 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 if (flags == NULL) {
1004 flags = &local_flags;
1005 local_flags.cf_flags = 0;
1006 }
1007 v = PySys_GetObject("ps1");
1008 if (v == NULL) {
1009 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1010 Py_XDECREF(v);
1011 }
1012 v = PySys_GetObject("ps2");
1013 if (v == NULL) {
1014 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1015 Py_XDECREF(v);
1016 }
1017 for (;;) {
1018 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1019 PRINT_TOTAL_REFS();
1020 if (ret == E_EOF)
1021 return 0;
1022 /*
1023 if (ret == E_NOMEM)
1024 return -1;
1025 */
1026 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001027}
1028
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001029/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001030static int PARSER_FLAGS(PyCompilerFlags *flags)
1031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 int parser_flags = 0;
1033 if (!flags)
1034 return 0;
1035 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1036 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1037 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1038 parser_flags |= PyPARSE_IGNORE_COOKIE;
1039 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1040 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1041 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001042}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001043
Thomas Wouters89f507f2006-12-13 04:49:30 +00001044#if 0
1045/* Keep an example of flags with future keyword support. */
1046#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1048 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1049 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1050 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001051#endif
1052
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001053int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001054PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 PyObject *m, *d, *v, *w, *oenc = NULL;
1057 mod_ty mod;
1058 PyArena *arena;
1059 char *ps1 = "", *ps2 = "", *enc = NULL;
1060 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 if (fp == stdin) {
1063 /* Fetch encoding from sys.stdin */
1064 v = PySys_GetObject("stdin");
1065 if (v == NULL || v == Py_None)
1066 return -1;
1067 oenc = PyObject_GetAttrString(v, "encoding");
1068 if (!oenc)
1069 return -1;
1070 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001071 if (enc == NULL)
1072 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 }
1074 v = PySys_GetObject("ps1");
1075 if (v != NULL) {
1076 v = PyObject_Str(v);
1077 if (v == NULL)
1078 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001079 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001081 if (ps1 == NULL) {
1082 PyErr_Clear();
1083 ps1 = "";
1084 }
1085 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 }
1087 w = PySys_GetObject("ps2");
1088 if (w != NULL) {
1089 w = PyObject_Str(w);
1090 if (w == NULL)
1091 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001092 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001094 if (ps2 == NULL) {
1095 PyErr_Clear();
1096 ps2 = "";
1097 }
1098 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 }
1100 arena = PyArena_New();
1101 if (arena == NULL) {
1102 Py_XDECREF(v);
1103 Py_XDECREF(w);
1104 Py_XDECREF(oenc);
1105 return -1;
1106 }
1107 mod = PyParser_ASTFromFile(fp, filename, enc,
1108 Py_single_input, ps1, ps2,
1109 flags, &errcode, arena);
1110 Py_XDECREF(v);
1111 Py_XDECREF(w);
1112 Py_XDECREF(oenc);
1113 if (mod == NULL) {
1114 PyArena_Free(arena);
1115 if (errcode == E_EOF) {
1116 PyErr_Clear();
1117 return E_EOF;
1118 }
1119 PyErr_Print();
1120 return -1;
1121 }
1122 m = PyImport_AddModule("__main__");
1123 if (m == NULL) {
1124 PyArena_Free(arena);
1125 return -1;
1126 }
1127 d = PyModule_GetDict(m);
1128 v = run_mod(mod, filename, d, d, flags, arena);
1129 PyArena_Free(arena);
1130 flush_io();
1131 if (v == NULL) {
1132 PyErr_Print();
1133 return -1;
1134 }
1135 Py_DECREF(v);
1136 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001137}
1138
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001139/* Check whether a file maybe a pyc file: Look at the extension,
1140 the file type, and, if we may close it, at the first few bytes. */
1141
1142static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001143maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1146 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 /* Only look into the file if we are allowed to close it, since
1149 it then should also be seekable. */
1150 if (closeit) {
1151 /* Read only two bytes of the magic. If the file was opened in
1152 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1153 be read as they are on disk. */
1154 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1155 unsigned char buf[2];
1156 /* Mess: In case of -x, the stream is NOT at its start now,
1157 and ungetc() was used to push back the first newline,
1158 which makes the current stream position formally undefined,
1159 and a x-platform nightmare.
1160 Unfortunately, we have no direct way to know whether -x
1161 was specified. So we use a terrible hack: if the current
1162 stream position is not 0, we assume -x was specified, and
1163 give up. Bug 132850 on SourceForge spells out the
1164 hopelessness of trying anything else (fseek and ftell
1165 don't work predictably x-platform for text-mode files).
1166 */
1167 int ispyc = 0;
1168 if (ftell(fp) == 0) {
1169 if (fread(buf, 1, 2, fp) == 2 &&
1170 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1171 ispyc = 1;
1172 rewind(fp);
1173 }
1174 return ispyc;
1175 }
1176 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001177}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001178
Guido van Rossum0df002c2000-08-27 19:21:52 +00001179int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001180PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 PyObject *m, *d, *v;
1184 const char *ext;
1185 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 m = PyImport_AddModule("__main__");
1188 if (m == NULL)
1189 return -1;
1190 d = PyModule_GetDict(m);
1191 if (PyDict_GetItemString(d, "__file__") == NULL) {
1192 PyObject *f;
Victor Stinner0fe25a42010-06-17 23:08:50 +00001193 f = PyUnicode_FromString(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 if (f == NULL)
1195 return -1;
1196 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1197 Py_DECREF(f);
1198 return -1;
1199 }
1200 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1201 return -1;
1202 set_file_name = 1;
1203 Py_DECREF(f);
1204 }
1205 len = strlen(filename);
1206 ext = filename + len - (len > 4 ? 4 : 0);
1207 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1208 /* Try to run a pyc file. First, re-open in binary */
1209 if (closeit)
1210 fclose(fp);
1211 if ((fp = fopen(filename, "rb")) == NULL) {
1212 fprintf(stderr, "python: Can't reopen .pyc file\n");
1213 ret = -1;
1214 goto done;
1215 }
1216 /* Turn on optimization if a .pyo file is given */
1217 if (strcmp(ext, ".pyo") == 0)
1218 Py_OptimizeFlag = 1;
1219 v = run_pyc_file(fp, filename, d, d, flags);
1220 } else {
1221 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1222 closeit, flags);
1223 }
1224 flush_io();
1225 if (v == NULL) {
1226 PyErr_Print();
1227 ret = -1;
1228 goto done;
1229 }
1230 Py_DECREF(v);
1231 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001232 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1234 PyErr_Clear();
1235 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001236}
1237
1238int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001239PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 PyObject *m, *d, *v;
1242 m = PyImport_AddModule("__main__");
1243 if (m == NULL)
1244 return -1;
1245 d = PyModule_GetDict(m);
1246 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1247 if (v == NULL) {
1248 PyErr_Print();
1249 return -1;
1250 }
1251 Py_DECREF(v);
1252 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001253}
1254
Barry Warsaw035574d1997-08-29 22:07:17 +00001255static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001256parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 long hold;
1260 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 /* old style errors */
1263 if (PyTuple_Check(err))
1264 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1265 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 if (! (v = PyObject_GetAttrString(err, "msg")))
1270 goto finally;
1271 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (!(v = PyObject_GetAttrString(err, "filename")))
1274 goto finally;
1275 if (v == Py_None)
1276 *filename = NULL;
1277 else if (! (*filename = _PyUnicode_AsString(v)))
1278 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 Py_DECREF(v);
1281 if (!(v = PyObject_GetAttrString(err, "lineno")))
1282 goto finally;
1283 hold = PyLong_AsLong(v);
1284 Py_DECREF(v);
1285 v = NULL;
1286 if (hold < 0 && PyErr_Occurred())
1287 goto finally;
1288 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (!(v = PyObject_GetAttrString(err, "offset")))
1291 goto finally;
1292 if (v == Py_None) {
1293 *offset = -1;
1294 Py_DECREF(v);
1295 v = NULL;
1296 } else {
1297 hold = PyLong_AsLong(v);
1298 Py_DECREF(v);
1299 v = NULL;
1300 if (hold < 0 && PyErr_Occurred())
1301 goto finally;
1302 *offset = (int)hold;
1303 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (!(v = PyObject_GetAttrString(err, "text")))
1306 goto finally;
1307 if (v == Py_None)
1308 *text = NULL;
1309 else if (!PyUnicode_Check(v) ||
1310 !(*text = _PyUnicode_AsString(v)))
1311 goto finally;
1312 Py_DECREF(v);
1313 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001314
1315finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 Py_XDECREF(v);
1317 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001318}
1319
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001320void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001321PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001324}
1325
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001326static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001327print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 char *nl;
1330 if (offset >= 0) {
1331 if (offset > 0 && offset == (int)strlen(text))
1332 offset--;
1333 for (;;) {
1334 nl = strchr(text, '\n');
1335 if (nl == NULL || nl-text >= offset)
1336 break;
1337 offset -= (int)(nl+1-text);
1338 text = nl+1;
1339 }
1340 while (*text == ' ' || *text == '\t') {
1341 text++;
1342 offset--;
1343 }
1344 }
1345 PyFile_WriteString(" ", f);
1346 PyFile_WriteString(text, f);
1347 if (*text == '\0' || text[strlen(text)-1] != '\n')
1348 PyFile_WriteString("\n", f);
1349 if (offset == -1)
1350 return;
1351 PyFile_WriteString(" ", f);
1352 offset--;
1353 while (offset > 0) {
1354 PyFile_WriteString(" ", f);
1355 offset--;
1356 }
1357 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001358}
1359
Guido van Rossum66e8e862001-03-23 17:54:43 +00001360static void
1361handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 PyObject *exception, *value, *tb;
1364 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 if (Py_InspectFlag)
1367 /* Don't exit if -i flag was given. This flag is set to 0
1368 * when entering interactive mode for inspecting. */
1369 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 PyErr_Fetch(&exception, &value, &tb);
1372 fflush(stdout);
1373 if (value == NULL || value == Py_None)
1374 goto done;
1375 if (PyExceptionInstance_Check(value)) {
1376 /* The error code should be in the `code' attribute. */
1377 PyObject *code = PyObject_GetAttrString(value, "code");
1378 if (code) {
1379 Py_DECREF(value);
1380 value = code;
1381 if (value == Py_None)
1382 goto done;
1383 }
1384 /* If we failed to dig out the 'code' attribute,
1385 just let the else clause below print the error. */
1386 }
1387 if (PyLong_Check(value))
1388 exitcode = (int)PyLong_AsLong(value);
1389 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001390 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001391 if (sys_stderr != NULL && sys_stderr != Py_None) {
1392 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1393 } else {
1394 PyObject_Print(value, stderr, Py_PRINT_RAW);
1395 fflush(stderr);
1396 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 PySys_WriteStderr("\n");
1398 exitcode = 1;
1399 }
Tim Peterscf615b52003-04-19 18:47:02 +00001400 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 /* Restore and clear the exception info, in order to properly decref
1402 * the exception, value, and traceback. If we just exit instead,
1403 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1404 * some finalizers from running.
1405 */
1406 PyErr_Restore(exception, value, tb);
1407 PyErr_Clear();
1408 Py_Exit(exitcode);
1409 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001410}
1411
1412void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001413PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1418 handle_system_exit();
1419 }
1420 PyErr_Fetch(&exception, &v, &tb);
1421 if (exception == NULL)
1422 return;
1423 PyErr_NormalizeException(&exception, &v, &tb);
1424 if (tb == NULL) {
1425 tb = Py_None;
1426 Py_INCREF(tb);
1427 }
1428 PyException_SetTraceback(v, tb);
1429 if (exception == NULL)
1430 return;
1431 /* Now we know v != NULL too */
1432 if (set_sys_last_vars) {
1433 PySys_SetObject("last_type", exception);
1434 PySys_SetObject("last_value", v);
1435 PySys_SetObject("last_traceback", tb);
1436 }
1437 hook = PySys_GetObject("excepthook");
1438 if (hook) {
1439 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1440 PyObject *result = PyEval_CallObject(hook, args);
1441 if (result == NULL) {
1442 PyObject *exception2, *v2, *tb2;
1443 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1444 handle_system_exit();
1445 }
1446 PyErr_Fetch(&exception2, &v2, &tb2);
1447 PyErr_NormalizeException(&exception2, &v2, &tb2);
1448 /* It should not be possible for exception2 or v2
1449 to be NULL. However PyErr_Display() can't
1450 tolerate NULLs, so just be safe. */
1451 if (exception2 == NULL) {
1452 exception2 = Py_None;
1453 Py_INCREF(exception2);
1454 }
1455 if (v2 == NULL) {
1456 v2 = Py_None;
1457 Py_INCREF(v2);
1458 }
1459 fflush(stdout);
1460 PySys_WriteStderr("Error in sys.excepthook:\n");
1461 PyErr_Display(exception2, v2, tb2);
1462 PySys_WriteStderr("\nOriginal exception was:\n");
1463 PyErr_Display(exception, v, tb);
1464 Py_DECREF(exception2);
1465 Py_DECREF(v2);
1466 Py_XDECREF(tb2);
1467 }
1468 Py_XDECREF(result);
1469 Py_XDECREF(args);
1470 } else {
1471 PySys_WriteStderr("sys.excepthook is missing\n");
1472 PyErr_Display(exception, v, tb);
1473 }
1474 Py_XDECREF(exception);
1475 Py_XDECREF(v);
1476 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001477}
1478
Benjamin Petersone6528212008-07-15 15:32:09 +00001479static void
1480print_exception(PyObject *f, PyObject *value)
1481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 int err = 0;
1483 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (!PyExceptionInstance_Check(value)) {
1486 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1487 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1488 PyFile_WriteString(" found\n", f);
1489 return;
1490 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 Py_INCREF(value);
1493 fflush(stdout);
1494 type = (PyObject *) Py_TYPE(value);
1495 tb = PyException_GetTraceback(value);
1496 if (tb && tb != Py_None)
1497 err = PyTraceBack_Print(tb, f);
1498 if (err == 0 &&
1499 PyObject_HasAttrString(value, "print_file_and_line"))
1500 {
1501 PyObject *message;
1502 const char *filename, *text;
1503 int lineno, offset;
1504 if (!parse_syntax_error(value, &message, &filename,
1505 &lineno, &offset, &text))
1506 PyErr_Clear();
1507 else {
1508 char buf[10];
1509 PyFile_WriteString(" File \"", f);
1510 if (filename == NULL)
1511 PyFile_WriteString("<string>", f);
1512 else
1513 PyFile_WriteString(filename, f);
1514 PyFile_WriteString("\", line ", f);
1515 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1516 PyFile_WriteString(buf, f);
1517 PyFile_WriteString("\n", f);
1518 if (text != NULL)
1519 print_error_text(f, offset, text);
1520 Py_DECREF(value);
1521 value = message;
1522 /* Can't be bothered to check all those
1523 PyFile_WriteString() calls */
1524 if (PyErr_Occurred())
1525 err = -1;
1526 }
1527 }
1528 if (err) {
1529 /* Don't do anything else */
1530 }
1531 else {
1532 PyObject* moduleName;
1533 char* className;
1534 assert(PyExceptionClass_Check(type));
1535 className = PyExceptionClass_Name(type);
1536 if (className != NULL) {
1537 char *dot = strrchr(className, '.');
1538 if (dot != NULL)
1539 className = dot+1;
1540 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 moduleName = PyObject_GetAttrString(type, "__module__");
1543 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1544 {
1545 Py_DECREF(moduleName);
1546 err = PyFile_WriteString("<unknown>", f);
1547 }
1548 else {
1549 char* modstr = _PyUnicode_AsString(moduleName);
1550 if (modstr && strcmp(modstr, "builtins"))
1551 {
1552 err = PyFile_WriteString(modstr, f);
1553 err += PyFile_WriteString(".", f);
1554 }
1555 Py_DECREF(moduleName);
1556 }
1557 if (err == 0) {
1558 if (className == NULL)
1559 err = PyFile_WriteString("<unknown>", f);
1560 else
1561 err = PyFile_WriteString(className, f);
1562 }
1563 }
1564 if (err == 0 && (value != Py_None)) {
1565 PyObject *s = PyObject_Str(value);
1566 /* only print colon if the str() of the
1567 object is not the empty string
1568 */
1569 if (s == NULL)
1570 err = -1;
1571 else if (!PyUnicode_Check(s) ||
1572 PyUnicode_GetSize(s) != 0)
1573 err = PyFile_WriteString(": ", f);
1574 if (err == 0)
1575 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1576 Py_XDECREF(s);
1577 }
1578 /* try to write a newline in any case */
1579 err += PyFile_WriteString("\n", f);
1580 Py_XDECREF(tb);
1581 Py_DECREF(value);
1582 /* If an error happened here, don't show it.
1583 XXX This is wrong, but too many callers rely on this behavior. */
1584 if (err != 0)
1585 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001586}
1587
1588static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 "\nThe above exception was the direct cause "
1590 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001591
1592static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 "\nDuring handling of the above exception, "
1594 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001595
1596static void
1597print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 int err = 0, res;
1600 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 if (seen != NULL) {
1603 /* Exception chaining */
1604 if (PySet_Add(seen, value) == -1)
1605 PyErr_Clear();
1606 else if (PyExceptionInstance_Check(value)) {
1607 cause = PyException_GetCause(value);
1608 context = PyException_GetContext(value);
1609 if (cause) {
1610 res = PySet_Contains(seen, cause);
1611 if (res == -1)
1612 PyErr_Clear();
1613 if (res == 0) {
1614 print_exception_recursive(
1615 f, cause, seen);
1616 err |= PyFile_WriteString(
1617 cause_message, f);
1618 }
1619 }
1620 else if (context) {
1621 res = PySet_Contains(seen, context);
1622 if (res == -1)
1623 PyErr_Clear();
1624 if (res == 0) {
1625 print_exception_recursive(
1626 f, context, seen);
1627 err |= PyFile_WriteString(
1628 context_message, f);
1629 }
1630 }
1631 Py_XDECREF(context);
1632 Py_XDECREF(cause);
1633 }
1634 }
1635 print_exception(f, value);
1636 if (err != 0)
1637 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001638}
1639
Thomas Wouters477c8d52006-05-27 19:21:47 +00001640void
1641PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 PyObject *seen;
1644 PyObject *f = PySys_GetObject("stderr");
1645 if (f == Py_None) {
1646 /* pass */
1647 }
1648 else if (f == NULL) {
1649 _PyObject_Dump(value);
1650 fprintf(stderr, "lost sys.stderr\n");
1651 }
1652 else {
1653 /* We choose to ignore seen being possibly NULL, and report
1654 at least the main exception (it could be a MemoryError).
1655 */
1656 seen = PySet_New(NULL);
1657 if (seen == NULL)
1658 PyErr_Clear();
1659 print_exception_recursive(f, value, seen);
1660 Py_XDECREF(seen);
1661 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001662}
1663
Guido van Rossum82598051997-03-05 00:20:32 +00001664PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001665PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 PyObject *ret = NULL;
1669 mod_ty mod;
1670 PyArena *arena = PyArena_New();
1671 if (arena == NULL)
1672 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1675 if (mod != NULL)
1676 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1677 PyArena_Free(arena);
1678 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001679}
1680
1681PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001682PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyObject *ret;
1686 mod_ty mod;
1687 PyArena *arena = PyArena_New();
1688 if (arena == NULL)
1689 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1692 flags, NULL, arena);
1693 if (closeit)
1694 fclose(fp);
1695 if (mod == NULL) {
1696 PyArena_Free(arena);
1697 return NULL;
1698 }
1699 ret = run_mod(mod, filename, globals, locals, flags, arena);
1700 PyArena_Free(arena);
1701 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001702}
1703
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001704static void
1705flush_io(void)
1706{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 PyObject *f, *r;
1708 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 /* Save the current exception */
1711 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 f = PySys_GetObject("stderr");
1714 if (f != NULL) {
1715 r = PyObject_CallMethod(f, "flush", "");
1716 if (r)
1717 Py_DECREF(r);
1718 else
1719 PyErr_Clear();
1720 }
1721 f = PySys_GetObject("stdout");
1722 if (f != NULL) {
1723 r = PyObject_CallMethod(f, "flush", "");
1724 if (r)
1725 Py_DECREF(r);
1726 else
1727 PyErr_Clear();
1728 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001731}
1732
Guido van Rossum82598051997-03-05 00:20:32 +00001733static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001734run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyCodeObject *co;
1738 PyObject *v;
1739 co = PyAST_Compile(mod, filename, flags, arena);
1740 if (co == NULL)
1741 return NULL;
1742 v = PyEval_EvalCode(co, globals, locals);
1743 Py_DECREF(co);
1744 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001745}
1746
Guido van Rossum82598051997-03-05 00:20:32 +00001747static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001748run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 PyCodeObject *co;
1752 PyObject *v;
1753 long magic;
1754 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 magic = PyMarshal_ReadLongFromFile(fp);
1757 if (magic != PyImport_GetMagicNumber()) {
1758 PyErr_SetString(PyExc_RuntimeError,
1759 "Bad magic number in .pyc file");
1760 return NULL;
1761 }
1762 (void) PyMarshal_ReadLongFromFile(fp);
1763 v = PyMarshal_ReadLastObjectFromFile(fp);
1764 fclose(fp);
1765 if (v == NULL || !PyCode_Check(v)) {
1766 Py_XDECREF(v);
1767 PyErr_SetString(PyExc_RuntimeError,
1768 "Bad code object in .pyc file");
1769 return NULL;
1770 }
1771 co = (PyCodeObject *)v;
1772 v = PyEval_EvalCode(co, globals, locals);
1773 if (v && flags)
1774 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1775 Py_DECREF(co);
1776 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001777}
1778
Guido van Rossum82598051997-03-05 00:20:32 +00001779PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001780Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 PyCodeObject *co;
1784 mod_ty mod;
1785 PyArena *arena = PyArena_New();
1786 if (arena == NULL)
1787 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1790 if (mod == NULL) {
1791 PyArena_Free(arena);
1792 return NULL;
1793 }
1794 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1795 PyObject *result = PyAST_mod2obj(mod);
1796 PyArena_Free(arena);
1797 return result;
1798 }
1799 co = PyAST_Compile(mod, filename, flags, arena);
1800 PyArena_Free(arena);
1801 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001802}
1803
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001804struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001805Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 struct symtable *st;
1808 mod_ty mod;
1809 PyCompilerFlags flags;
1810 PyArena *arena = PyArena_New();
1811 if (arena == NULL)
1812 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 flags.cf_flags = 0;
1815 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1816 if (mod == NULL) {
1817 PyArena_Free(arena);
1818 return NULL;
1819 }
1820 st = PySymtable_Build(mod, filename, 0);
1821 PyArena_Free(arena);
1822 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001823}
1824
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825/* Preferred access to parser is through AST. */
1826mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001827PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 mod_ty mod;
1831 PyCompilerFlags localflags;
1832 perrdetail err;
1833 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1836 &_PyParser_Grammar, start, &err,
1837 &iflags);
1838 if (flags == NULL) {
1839 localflags.cf_flags = 0;
1840 flags = &localflags;
1841 }
1842 if (n) {
1843 flags->cf_flags |= iflags & PyCF_MASK;
1844 mod = PyAST_FromNode(n, flags, filename, arena);
1845 PyNode_Free(n);
1846 return mod;
1847 }
1848 else {
1849 err_input(&err);
1850 return NULL;
1851 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001852}
1853
1854mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001855PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 int start, char *ps1,
1857 char *ps2, PyCompilerFlags *flags, int *errcode,
1858 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 mod_ty mod;
1861 PyCompilerFlags localflags;
1862 perrdetail err;
1863 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1866 &_PyParser_Grammar,
1867 start, ps1, ps2, &err, &iflags);
1868 if (flags == NULL) {
1869 localflags.cf_flags = 0;
1870 flags = &localflags;
1871 }
1872 if (n) {
1873 flags->cf_flags |= iflags & PyCF_MASK;
1874 mod = PyAST_FromNode(n, flags, filename, arena);
1875 PyNode_Free(n);
1876 return mod;
1877 }
1878 else {
1879 err_input(&err);
1880 if (errcode)
1881 *errcode = err.error;
1882 return NULL;
1883 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001884}
1885
Guido van Rossuma110aa61994-08-29 12:50:44 +00001886/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001887
Guido van Rossuma110aa61994-08-29 12:50:44 +00001888node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001889PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001890{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 perrdetail err;
1892 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1893 &_PyParser_Grammar,
1894 start, NULL, NULL, &err, flags);
1895 if (n == NULL)
1896 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001899}
1900
Guido van Rossuma110aa61994-08-29 12:50:44 +00001901/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001902
Guido van Rossuma110aa61994-08-29 12:50:44 +00001903node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001904PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 perrdetail err;
1907 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1908 start, &err, flags);
1909 if (n == NULL)
1910 err_input(&err);
1911 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001912}
1913
1914node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001915PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 perrdetail err;
1919 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1920 &_PyParser_Grammar, start, &err, flags);
1921 if (n == NULL)
1922 err_input(&err);
1923 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001924}
1925
1926node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001927PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001930}
1931
Guido van Rossum66ebd912003-04-17 16:02:26 +00001932/* May want to move a more generalized form of this to parsetok.c or
1933 even parser modules. */
1934
1935void
1936PyParser_SetError(perrdetail *err)
1937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001939}
1940
Guido van Rossuma110aa61994-08-29 12:50:44 +00001941/* Set the error appropriate to the given input error code (see errcode.h) */
1942
1943static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001944err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 PyObject *v, *w, *errtype, *errtext;
1947 PyObject *msg_obj = NULL;
1948 char *msg = NULL;
1949 errtype = PyExc_SyntaxError;
1950 switch (err->error) {
1951 case E_ERROR:
1952 return;
1953 case E_SYNTAX:
1954 errtype = PyExc_IndentationError;
1955 if (err->expected == INDENT)
1956 msg = "expected an indented block";
1957 else if (err->token == INDENT)
1958 msg = "unexpected indent";
1959 else if (err->token == DEDENT)
1960 msg = "unexpected unindent";
1961 else {
1962 errtype = PyExc_SyntaxError;
1963 msg = "invalid syntax";
1964 }
1965 break;
1966 case E_TOKEN:
1967 msg = "invalid token";
1968 break;
1969 case E_EOFS:
1970 msg = "EOF while scanning triple-quoted string literal";
1971 break;
1972 case E_EOLS:
1973 msg = "EOL while scanning string literal";
1974 break;
1975 case E_INTR:
1976 if (!PyErr_Occurred())
1977 PyErr_SetNone(PyExc_KeyboardInterrupt);
1978 goto cleanup;
1979 case E_NOMEM:
1980 PyErr_NoMemory();
1981 goto cleanup;
1982 case E_EOF:
1983 msg = "unexpected EOF while parsing";
1984 break;
1985 case E_TABSPACE:
1986 errtype = PyExc_TabError;
1987 msg = "inconsistent use of tabs and spaces in indentation";
1988 break;
1989 case E_OVERFLOW:
1990 msg = "expression too long";
1991 break;
1992 case E_DEDENT:
1993 errtype = PyExc_IndentationError;
1994 msg = "unindent does not match any outer indentation level";
1995 break;
1996 case E_TOODEEP:
1997 errtype = PyExc_IndentationError;
1998 msg = "too many levels of indentation";
1999 break;
2000 case E_DECODE: {
2001 PyObject *type, *value, *tb;
2002 PyErr_Fetch(&type, &value, &tb);
2003 msg = "unknown decode error";
2004 if (value != NULL)
2005 msg_obj = PyObject_Str(value);
2006 Py_XDECREF(type);
2007 Py_XDECREF(value);
2008 Py_XDECREF(tb);
2009 break;
2010 }
2011 case E_LINECONT:
2012 msg = "unexpected character after line continuation character";
2013 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 case E_IDENTIFIER:
2016 msg = "invalid character in identifier";
2017 break;
2018 default:
2019 fprintf(stderr, "error=%d\n", err->error);
2020 msg = "unknown parsing error";
2021 break;
2022 }
2023 /* err->text may not be UTF-8 in case of decoding errors.
2024 Explicitly convert to an object. */
2025 if (!err->text) {
2026 errtext = Py_None;
2027 Py_INCREF(Py_None);
2028 } else {
2029 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2030 "replace");
2031 }
2032 v = Py_BuildValue("(ziiN)", err->filename,
2033 err->lineno, err->offset, errtext);
2034 if (v != NULL) {
2035 if (msg_obj)
2036 w = Py_BuildValue("(OO)", msg_obj, v);
2037 else
2038 w = Py_BuildValue("(sO)", msg, v);
2039 } else
2040 w = NULL;
2041 Py_XDECREF(v);
2042 PyErr_SetObject(errtype, w);
2043 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002044cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 Py_XDECREF(msg_obj);
2046 if (err->text != NULL) {
2047 PyObject_FREE(err->text);
2048 err->text = NULL;
2049 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002050}
2051
2052/* Print fatal error message and abort */
2053
2054void
Tim Peters7c321a82002-07-09 02:57:01 +00002055Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 fprintf(stderr, "Fatal Python error: %s\n", msg);
2058 fflush(stderr); /* it helps in Windows debug build */
2059 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002060 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002062#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 {
2064 size_t len = strlen(msg);
2065 WCHAR* buffer;
2066 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 /* Convert the message to wchar_t. This uses a simple one-to-one
2069 conversion, assuming that the this error message actually uses ASCII
2070 only. If this ceases to be true, we will have to convert. */
2071 buffer = alloca( (len+1) * (sizeof *buffer));
2072 for( i=0; i<=len; ++i)
2073 buffer[i] = msg[i];
2074 OutputDebugStringW(L"Fatal Python error: ");
2075 OutputDebugStringW(buffer);
2076 OutputDebugStringW(L"\n");
2077 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002078#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002080#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002081#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002083}
2084
2085/* Clean up and exit */
2086
Guido van Rossuma110aa61994-08-29 12:50:44 +00002087#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002088#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002089#endif
2090
Collin Winter670e6922007-03-21 02:57:17 +00002091static void (*pyexitfunc)(void) = NULL;
2092/* For the atexit module. */
2093void _Py_PyAtExit(void (*func)(void))
2094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002096}
2097
2098static void
2099call_py_exitfuncs(void)
2100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (pyexitfunc == NULL)
2102 return;
Collin Winter670e6922007-03-21 02:57:17 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 (*pyexitfunc)();
2105 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002106}
2107
Antoine Pitrou011bd622009-10-20 21:52:47 +00002108/* Wait until threading._shutdown completes, provided
2109 the threading module was imported in the first place.
2110 The shutdown routine will wait until all non-daemon
2111 "threading" threads have completed. */
2112static void
2113wait_for_thread_shutdown(void)
2114{
2115#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 PyObject *result;
2117 PyThreadState *tstate = PyThreadState_GET();
2118 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2119 "threading");
2120 if (threading == NULL) {
2121 /* threading not imported */
2122 PyErr_Clear();
2123 return;
2124 }
2125 result = PyObject_CallMethod(threading, "_shutdown", "");
2126 if (result == NULL) {
2127 PyErr_WriteUnraisable(threading);
2128 }
2129 else {
2130 Py_DECREF(result);
2131 }
2132 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002133#endif
2134}
2135
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002136#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002137static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002138static int nexitfuncs = 0;
2139
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002140int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 if (nexitfuncs >= NEXITFUNCS)
2143 return -1;
2144 exitfuncs[nexitfuncs++] = func;
2145 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002146}
2147
Guido van Rossumcc283f51997-08-05 02:22:03 +00002148static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002149call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 while (nexitfuncs > 0)
2152 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 fflush(stdout);
2155 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002156}
2157
2158void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002159Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002164}
2165
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002166static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002167initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002168{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002169#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002171#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002172#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002174#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002175#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002177#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002179}
2180
Guido van Rossum7433b121997-02-14 19:45:36 +00002181
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002182/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2183 *
2184 * All of the code in this function must only use async-signal-safe functions,
2185 * listed at `man 7 signal` or
2186 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2187 */
2188void
2189_Py_RestoreSignals(void)
2190{
2191#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002193#endif
2194#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002196#endif
2197#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002199#endif
2200}
2201
2202
Guido van Rossum7433b121997-02-14 19:45:36 +00002203/*
2204 * The file descriptor fd is considered ``interactive'' if either
2205 * a) isatty(fd) is TRUE, or
2206 * b) the -i flag was given, and the filename associated with
2207 * the descriptor is NULL or "<stdin>" or "???".
2208 */
2209int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002210Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (isatty((int)fileno(fp)))
2213 return 1;
2214 if (!Py_InteractiveFlag)
2215 return 0;
2216 return (filename == NULL) ||
2217 (strcmp(filename, "<stdin>") == 0) ||
2218 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002219}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002220
2221
Tim Petersd08e3822003-04-17 15:24:21 +00002222#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002223#if defined(WIN32) && defined(_MSC_VER)
2224
2225/* Stack checking for Microsoft C */
2226
2227#include <malloc.h>
2228#include <excpt.h>
2229
Fred Drakee8de31c2000-08-31 05:38:39 +00002230/*
2231 * Return non-zero when we run out of memory on the stack; zero otherwise.
2232 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002233int
Fred Drake399739f2000-08-31 05:52:44 +00002234PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 __try {
2237 /* alloca throws a stack overflow exception if there's
2238 not enough space left on the stack */
2239 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2240 return 0;
2241 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2242 EXCEPTION_EXECUTE_HANDLER :
2243 EXCEPTION_CONTINUE_SEARCH) {
2244 int errcode = _resetstkoflw();
2245 if (errcode == 0)
2246 {
2247 Py_FatalError("Could not reset the stack!");
2248 }
2249 }
2250 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002251}
2252
2253#endif /* WIN32 && _MSC_VER */
2254
2255/* Alternate implementations can be added here... */
2256
2257#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002258
2259
2260/* Wrappers around sigaction() or signal(). */
2261
2262PyOS_sighandler_t
2263PyOS_getsig(int sig)
2264{
2265#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 struct sigaction context;
2267 if (sigaction(sig, NULL, &context) == -1)
2268 return SIG_ERR;
2269 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002270#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002272/* Special signal handling for the secure CRT in Visual Studio 2005 */
2273#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 switch (sig) {
2275 /* Only these signals are valid */
2276 case SIGINT:
2277 case SIGILL:
2278 case SIGFPE:
2279 case SIGSEGV:
2280 case SIGTERM:
2281 case SIGBREAK:
2282 case SIGABRT:
2283 break;
2284 /* Don't call signal() with other values or it will assert */
2285 default:
2286 return SIG_ERR;
2287 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002288#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 handler = signal(sig, SIG_IGN);
2290 if (handler != SIG_ERR)
2291 signal(sig, handler);
2292 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002293#endif
2294}
2295
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002296/*
2297 * All of the code in this function must only use async-signal-safe functions,
2298 * listed at `man 7 signal` or
2299 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2300 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002301PyOS_sighandler_t
2302PyOS_setsig(int sig, PyOS_sighandler_t handler)
2303{
2304#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 /* Some code in Modules/signalmodule.c depends on sigaction() being
2306 * used here if HAVE_SIGACTION is defined. Fix that if this code
2307 * changes to invalidate that assumption.
2308 */
2309 struct sigaction context, ocontext;
2310 context.sa_handler = handler;
2311 sigemptyset(&context.sa_mask);
2312 context.sa_flags = 0;
2313 if (sigaction(sig, &context, &ocontext) == -1)
2314 return SIG_ERR;
2315 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002316#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyOS_sighandler_t oldhandler;
2318 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002319#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002321#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002323#endif
2324}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002325
2326/* Deprecated C API functions still provided for binary compatiblity */
2327
2328#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002329PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002333}
2334
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002335#undef PyParser_SimpleParseString
2336PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002337PyParser_SimpleParseString(const char *str, int start)
2338{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002340}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002341
2342#undef PyRun_AnyFile
2343PyAPI_FUNC(int)
2344PyRun_AnyFile(FILE *fp, const char *name)
2345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002347}
2348
2349#undef PyRun_AnyFileEx
2350PyAPI_FUNC(int)
2351PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002354}
2355
2356#undef PyRun_AnyFileFlags
2357PyAPI_FUNC(int)
2358PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002361}
2362
2363#undef PyRun_File
2364PyAPI_FUNC(PyObject *)
2365PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002368}
2369
2370#undef PyRun_FileEx
2371PyAPI_FUNC(PyObject *)
2372PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002375}
2376
2377#undef PyRun_FileFlags
2378PyAPI_FUNC(PyObject *)
2379PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002383}
2384
2385#undef PyRun_SimpleFile
2386PyAPI_FUNC(int)
2387PyRun_SimpleFile(FILE *f, const char *p)
2388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002390}
2391
2392#undef PyRun_SimpleFileEx
2393PyAPI_FUNC(int)
2394PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002397}
2398
2399
2400#undef PyRun_String
2401PyAPI_FUNC(PyObject *)
2402PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002405}
2406
2407#undef PyRun_SimpleString
2408PyAPI_FUNC(int)
2409PyRun_SimpleString(const char *s)
2410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002412}
2413
2414#undef Py_CompileString
2415PyAPI_FUNC(PyObject *)
2416Py_CompileString(const char *str, const char *p, int s)
2417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002419}
2420
2421#undef PyRun_InteractiveOne
2422PyAPI_FUNC(int)
2423PyRun_InteractiveOne(FILE *f, const char *p)
2424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002426}
2427
2428#undef PyRun_InteractiveLoop
2429PyAPI_FUNC(int)
2430PyRun_InteractiveLoop(FILE *f, const char *p)
2431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002433}
2434
2435#ifdef __cplusplus
2436}
2437#endif