blob: a7a54ba71018155062d7e64db5a338bee90e2f9e [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
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000271 _PyTime_Init();
272
Victor Stinnerb744ba12010-05-15 12:27:16 +0000273 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 if (install_sigs)
276 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 /* Initialize warnings. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 if (PySys_HasWarnOptions()) {
280 PyObject *warnings_module = PyImport_ImportModule("warnings");
281 if (!warnings_module)
282 PyErr_Clear();
283 Py_XDECREF(warnings_module);
284 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 initmain(); /* Module __main__ */
287 if (initstdio() < 0)
288 Py_FatalError(
289 "Py_Initialize: can't initialize sys standard streams");
290
291 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000292#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000294#endif /* WITH_THREAD */
Victor Stinner52f6dd72010-03-12 14:45:56 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 if (!Py_NoSiteFlag)
297 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000298}
299
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000300void
301Py_Initialize(void)
302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000304}
305
306
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000307#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000308extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000309#endif
310
Guido van Rossume8432ac2007-07-09 15:04:50 +0000311/* Flush stdout and stderr */
312
Neal Norwitz2bad9702007-08-27 06:19:22 +0000313static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000314flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 PyObject *fout = PySys_GetObject("stdout");
317 PyObject *ferr = PySys_GetObject("stderr");
318 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (fout != NULL && fout != Py_None) {
321 tmp = PyObject_CallMethod(fout, "flush", "");
322 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000323 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 else
325 Py_DECREF(tmp);
326 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000327
Victor Stinner9467b212010-05-14 00:59:09 +0000328 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 tmp = PyObject_CallMethod(ferr, "flush", "");
330 if (tmp == NULL)
331 PyErr_Clear();
332 else
333 Py_DECREF(tmp);
334 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000335}
336
Guido van Rossum25ce5661997-08-02 03:10:38 +0000337/* Undo the effect of Py_Initialize().
338
339 Beware: if multiple interpreter and/or thread states exist, these
340 are not wiped out; only the current thread and interpreter state
341 are deleted. But since everything else is deleted, those other
342 interpreter and thread states should no longer be used.
343
344 (XXX We should do better, e.g. wipe out all interpreters and
345 threads.)
346
347 Locking: as above.
348
349*/
350
351void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000352Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 PyInterpreterState *interp;
355 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 if (!initialized)
358 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 /* The interpreter is still entirely intact at this point, and the
363 * exit funcs may be relying on that. In particular, if some thread
364 * or exit func is still waiting to do an import, the import machinery
365 * expects Py_IsInitialized() to return true. So don't say the
366 * interpreter is uninitialized until after the exit funcs have run.
367 * Note that Threading.py uses an exit func to do a join on all the
368 * threads created thru it, so this also protects pending imports in
369 * the threads created via Threading.
370 */
371 call_py_exitfuncs();
372 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 /* Flush stdout+stderr */
375 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 /* Get current thread state and interpreter pointer */
378 tstate = PyThreadState_GET();
379 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 /* Disable signal handling */
382 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 /* Clear type lookup cache */
385 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 /* Collect garbage. This may call finalizers; it's nice to call these
388 * before all modules are destroyed.
389 * XXX If a __del__ or weakref callback is triggered here, and tries to
390 * XXX import a module, bad things can happen, because Python no
391 * XXX longer believes it's initialized.
392 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
393 * XXX is easy to provoke that way. I've also seen, e.g.,
394 * XXX Exception exceptions.ImportError: 'No module named sha'
395 * XXX in <function callback at 0x008F5718> ignored
396 * XXX but I'm unclear on exactly how that one happens. In any case,
397 * XXX I haven't seen a real-life report of either of these.
398 */
399 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000400#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 /* With COUNT_ALLOCS, it helps to run GC multiple times:
402 each collection might release some types from the type
403 list, so they become garbage. */
404 while (PyGC_Collect() > 0)
405 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000406#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000407 /* We run this while most interpreter state is still alive, so that
408 debug information can be printed out */
409 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 /* Destroy all modules */
412 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 /* Flush stdout+stderr (again, in case more was printed) */
415 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 /* Collect final garbage. This disposes of cycles created by
418 * new-style class definitions, for example.
419 * XXX This is disabled because it caused too many problems. If
420 * XXX a __del__ or weakref callback triggers here, Python code has
421 * XXX a hard time running, because even the sys module has been
422 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
423 * XXX One symptom is a sequence of information-free messages
424 * XXX coming from threads (if a __del__ or callback is invoked,
425 * XXX other threads can execute too, and any exception they encounter
426 * XXX triggers a comedy of errors as subsystem after subsystem
427 * XXX fails to find what it *expects* to find in sys to help report
428 * XXX the exception and consequent unexpected failures). I've also
429 * XXX seen segfaults then, after adding print statements to the
430 * XXX Python code getting called.
431 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000432#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000434#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
437 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000440#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000442#endif
443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000445
Tim Peters9cf25ce2003-04-17 15:21:01 +0000446#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 /* Display all objects still alive -- this can invoke arbitrary
448 * __repr__ overrides, so requires a mostly-intact interpreter.
449 * Alas, a lot of stuff may still be alive now that will be cleaned
450 * up later.
451 */
452 if (Py_GETENV("PYTHONDUMPREFS"))
453 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000454#endif /* Py_TRACE_REFS */
455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 /* Clear interpreter state */
457 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 /* Now we decref the exception classes. After this point nothing
460 can raise an exception. That's okay, because each Fini() method
461 below has been checked to make sure no exceptions are ever
462 raised.
463 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000468#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000470#endif /* WITH_THREAD */
471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 /* Delete current thread */
473 PyThreadState_Swap(NULL);
474 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* Sundry finalizers */
477 PyMethod_Fini();
478 PyFrame_Fini();
479 PyCFunction_Fini();
480 PyTuple_Fini();
481 PyList_Fini();
482 PySet_Fini();
483 PyBytes_Fini();
484 PyByteArray_Fini();
485 PyLong_Fini();
486 PyFloat_Fini();
487 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* Cleanup Unicode implementation */
490 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000493 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 free((char*)Py_FileSystemDefaultEncoding);
495 Py_FileSystemDefaultEncoding = NULL;
496 }
Christian Heimesc8967002007-11-30 10:18:26 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 /* XXX Still allocated:
499 - various static ad-hoc pointers to interned strings
500 - int and float free list blocks
501 - whatever various modules and libraries allocate
502 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000505
Tim Peters269b2a62003-04-17 19:52:29 +0000506#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Display addresses (& refcnts) of all objects still alive.
508 * An address can be used to find the repr of the object, printed
509 * above by _Py_PrintReferences.
510 */
511 if (Py_GETENV("PYTHONDUMPREFS"))
512 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000513#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000514#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (Py_GETENV("PYTHONMALLOCSTATS"))
516 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000517#endif
518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000520}
521
522/* Create and initialize a new interpreter and thread, and return the
523 new thread. This requires that Py_Initialize() has been called
524 first.
525
526 Unsuccessful initialization yields a NULL pointer. Note that *no*
527 exception information is available even in this case -- the
528 exception information is held in the thread, and there is no
529 thread.
530
531 Locking: as above.
532
533*/
534
535PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000536Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 PyInterpreterState *interp;
539 PyThreadState *tstate, *save_tstate;
540 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (!initialized)
543 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 interp = PyInterpreterState_New();
546 if (interp == NULL)
547 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 tstate = PyThreadState_New(interp);
550 if (tstate == NULL) {
551 PyInterpreterState_Delete(interp);
552 return NULL;
553 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 interp->modules = PyDict_New();
560 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 bimod = _PyImport_FindExtension("builtins", "builtins");
563 if (bimod != NULL) {
564 interp->builtins = PyModule_GetDict(bimod);
565 if (interp->builtins == NULL)
566 goto handle_error;
567 Py_INCREF(interp->builtins);
568 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 /* initialize builtin exceptions */
571 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 sysmod = _PyImport_FindExtension("sys", "sys");
574 if (bimod != NULL && sysmod != NULL) {
575 PyObject *pstderr;
576 interp->sysdict = PyModule_GetDict(sysmod);
577 if (interp->sysdict == NULL)
578 goto handle_error;
579 Py_INCREF(interp->sysdict);
580 PySys_SetPath(Py_GetPath());
581 PyDict_SetItemString(interp->sysdict, "modules",
582 interp->modules);
583 /* Set up a preliminary stderr printer until we have enough
584 infrastructure for the io module in place. */
585 pstderr = PyFile_NewStdPrinter(fileno(stderr));
586 if (pstderr == NULL)
587 Py_FatalError("Py_Initialize: can't set preliminary stderr");
588 PySys_SetObject("stderr", pstderr);
589 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 _PyImportHooks_Init();
592 if (initstdio() < 0)
593 Py_FatalError(
594 "Py_Initialize: can't initialize sys standard streams");
595 initmain();
596 if (!Py_NoSiteFlag)
597 initsite();
598 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (!PyErr_Occurred())
601 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000602
Thomas Wouters89f507f2006-12-13 04:49:30 +0000603handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 PyErr_Print();
607 PyThreadState_Clear(tstate);
608 PyThreadState_Swap(save_tstate);
609 PyThreadState_Delete(tstate);
610 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000613}
614
615/* Delete an interpreter and its last thread. This requires that the
616 given thread state is current, that the thread has no remaining
617 frames, and that it is its interpreter's only remaining thread.
618 It is a fatal error to violate these constraints.
619
620 (Py_Finalize() doesn't have these constraints -- it zaps
621 everything, regardless.)
622
623 Locking: as above.
624
625*/
626
627void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000628Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (tstate != PyThreadState_GET())
633 Py_FatalError("Py_EndInterpreter: thread is not current");
634 if (tstate->frame != NULL)
635 Py_FatalError("Py_EndInterpreter: thread still has a frame");
636 if (tstate != interp->tstate_head || tstate->next != NULL)
637 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyImport_Cleanup();
640 PyInterpreterState_Clear(interp);
641 PyThreadState_Swap(NULL);
642 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000643}
644
Martin v. Löwis790465f2008-04-05 20:41:37 +0000645static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000646
647void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000648Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (pn && *pn)
651 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000652}
653
Martin v. Löwis790465f2008-04-05 20:41:37 +0000654wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000655Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000658}
659
Martin v. Löwis790465f2008-04-05 20:41:37 +0000660static wchar_t *default_home = NULL;
661static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000662
663void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000664Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000667}
668
Martin v. Löwis790465f2008-04-05 20:41:37 +0000669wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000670Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 wchar_t *home = default_home;
673 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
674 char* chome = Py_GETENV("PYTHONHOME");
675 if (chome) {
676 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
677 if (r != (size_t)-1 && r <= PATH_MAX)
678 home = env_home;
679 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 }
682 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000683}
684
Guido van Rossum6135a871995-01-09 17:53:26 +0000685/* Create __main__ module */
686
687static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000688initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 PyObject *m, *d;
691 m = PyImport_AddModule("__main__");
692 if (m == NULL)
693 Py_FatalError("can't create __main__ module");
694 d = PyModule_GetDict(m);
695 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
696 PyObject *bimod = PyImport_ImportModule("builtins");
697 if (bimod == NULL ||
698 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
699 Py_FatalError("can't add __builtins__ to __main__");
700 Py_DECREF(bimod);
701 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000702}
703
Victor Stinnerb744ba12010-05-15 12:27:16 +0000704static void
705initfsencoding(void)
706{
707 PyObject *codec;
708#if defined(HAVE_LANGINFO_H) && defined(CODESET)
709 char *codeset;
710
Victor Stinner7f84ab52010-06-11 00:36:33 +0000711 if (Py_FileSystemDefaultEncoding == NULL) {
712 /* On Unix, set the file system encoding according to the
713 user's preference, if the CODESET names a well-known
714 Python codec, and Py_FileSystemDefaultEncoding isn't
715 initialized by other means. Also set the encoding of
716 stdin and stdout if these are terminals. */
717 codeset = get_codeset();
718 if (codeset != NULL) {
719 Py_FileSystemDefaultEncoding = codeset;
720 Py_HasFileSystemDefaultEncoding = 0;
721 return;
722 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000723
Victor Stinner7f84ab52010-06-11 00:36:33 +0000724 PyErr_Clear();
725 fprintf(stderr,
726 "Unable to get the locale encoding: "
727 "fallback to utf-8\n");
728 Py_FileSystemDefaultEncoding = "utf-8";
729 Py_HasFileSystemDefaultEncoding = 1;
730 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000731#endif
732
733 /* the encoding is mbcs, utf-8 or ascii */
734 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
735 if (!codec) {
736 /* Such error can only occurs in critical situations: no more
737 * memory, import a module of the standard library failed,
738 * etc. */
739 Py_FatalError("Py_Initialize: unable to load the file system codec");
740 } else {
741 Py_DECREF(codec);
742 }
743}
744
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000745/* Import the site module (not into __main__ though) */
746
747static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000748initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 PyObject *m;
751 m = PyImport_ImportModule("site");
752 if (m == NULL) {
753 PyErr_Print();
754 Py_Finalize();
755 exit(1);
756 }
757 else {
758 Py_DECREF(m);
759 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000760}
761
Antoine Pitrou05608432009-01-09 18:53:14 +0000762static PyObject*
763create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 int fd, int write_mode, char* name,
765 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
768 const char* mode;
769 PyObject *line_buffering;
770 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 /* stdin is always opened in buffered mode, first because it shouldn't
773 make a difference in common use cases, second because TextIOWrapper
774 depends on the presence of a read1() method which only exists on
775 buffered streams.
776 */
777 if (Py_UnbufferedStdioFlag && write_mode)
778 buffering = 0;
779 else
780 buffering = -1;
781 if (write_mode)
782 mode = "wb";
783 else
784 mode = "rb";
785 buf = PyObject_CallMethod(io, "open", "isiOOOi",
786 fd, mode, buffering,
787 Py_None, Py_None, Py_None, 0);
788 if (buf == NULL)
789 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (buffering) {
792 raw = PyObject_GetAttrString(buf, "raw");
793 if (raw == NULL)
794 goto error;
795 }
796 else {
797 raw = buf;
798 Py_INCREF(raw);
799 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 text = PyUnicode_FromString(name);
802 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
803 goto error;
804 res = PyObject_CallMethod(raw, "isatty", "");
805 if (res == NULL)
806 goto error;
807 isatty = PyObject_IsTrue(res);
808 Py_DECREF(res);
809 if (isatty == -1)
810 goto error;
811 if (isatty || Py_UnbufferedStdioFlag)
812 line_buffering = Py_True;
813 else
814 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 Py_CLEAR(raw);
817 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
820 buf, encoding, errors,
821 "\n", line_buffering);
822 Py_CLEAR(buf);
823 if (stream == NULL)
824 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (write_mode)
827 mode = "w";
828 else
829 mode = "r";
830 text = PyUnicode_FromString(mode);
831 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
832 goto error;
833 Py_CLEAR(text);
834 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000835
836error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 Py_XDECREF(buf);
838 Py_XDECREF(stream);
839 Py_XDECREF(text);
840 Py_XDECREF(raw);
841 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000842}
843
Georg Brandl1a3284e2007-12-02 09:40:06 +0000844/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000845static int
846initstdio(void)
847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 PyObject *iomod = NULL, *wrapper;
849 PyObject *bimod = NULL;
850 PyObject *m;
851 PyObject *std = NULL;
852 int status = 0, fd;
853 PyObject * encoding_attr;
854 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 /* Hack to avoid a nasty recursion issue when Python is invoked
857 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
858 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
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 (!(m = PyImport_ImportModule("encodings.latin_1"))) {
864 goto error;
865 }
866 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (!(bimod = PyImport_ImportModule("builtins"))) {
869 goto error;
870 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (!(iomod = PyImport_ImportModule("io"))) {
873 goto error;
874 }
875 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
876 goto error;
877 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* Set builtins.open */
880 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
881 goto error;
882 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 encoding = Py_GETENV("PYTHONIOENCODING");
885 errors = NULL;
886 if (encoding) {
887 encoding = strdup(encoding);
888 errors = strchr(encoding, ':');
889 if (errors) {
890 *errors = '\0';
891 errors++;
892 }
893 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* Set sys.stdin */
896 fd = fileno(stdin);
897 /* Under some conditions stdin, stdout and stderr may not be connected
898 * and fileno() may point to an invalid file descriptor. For example
899 * GUI apps don't have valid standard streams by default.
900 */
901 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000902#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 std = Py_None;
904 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000905#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000907#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 }
909 else {
910 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
911 if (std == NULL)
912 goto error;
913 } /* if (fd < 0) */
914 PySys_SetObject("__stdin__", std);
915 PySys_SetObject("stdin", std);
916 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* Set sys.stdout */
919 fd = fileno(stdout);
920 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000921#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 std = Py_None;
923 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000924#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000926#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 }
928 else {
929 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
930 if (std == NULL)
931 goto error;
932 } /* if (fd < 0) */
933 PySys_SetObject("__stdout__", std);
934 PySys_SetObject("stdout", std);
935 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000936
Guido van Rossum98297ee2007-11-06 21:34:58 +0000937#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Set sys.stderr, replaces the preliminary stderr */
939 fd = fileno(stderr);
940 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000941#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 std = Py_None;
943 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000944#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000946#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 }
948 else {
949 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
950 if (std == NULL)
951 goto error;
952 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 /* Same as hack above, pre-import stderr's codec to avoid recursion
955 when import.c tries to write to stderr in verbose mode. */
956 encoding_attr = PyObject_GetAttrString(std, "encoding");
957 if (encoding_attr != NULL) {
958 const char * encoding;
959 encoding = _PyUnicode_AsString(encoding_attr);
960 if (encoding != NULL) {
961 _PyCodec_Lookup(encoding);
962 }
963 }
964 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PySys_SetObject("__stderr__", std);
967 PySys_SetObject("stderr", std);
968 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000969#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000972 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 status = -1;
974 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (encoding)
977 free(encoding);
978 Py_XDECREF(bimod);
979 Py_XDECREF(iomod);
980 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000981}
982
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000983/* Parse input from a file and execute it */
984
985int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000986PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (filename == NULL)
990 filename = "???";
991 if (Py_FdIsInteractive(fp, filename)) {
992 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
993 if (closeit)
994 fclose(fp);
995 return err;
996 }
997 else
998 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000999}
1000
1001int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001002PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 PyObject *v;
1005 int ret;
1006 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (flags == NULL) {
1009 flags = &local_flags;
1010 local_flags.cf_flags = 0;
1011 }
1012 v = PySys_GetObject("ps1");
1013 if (v == NULL) {
1014 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1015 Py_XDECREF(v);
1016 }
1017 v = PySys_GetObject("ps2");
1018 if (v == NULL) {
1019 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1020 Py_XDECREF(v);
1021 }
1022 for (;;) {
1023 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1024 PRINT_TOTAL_REFS();
1025 if (ret == E_EOF)
1026 return 0;
1027 /*
1028 if (ret == E_NOMEM)
1029 return -1;
1030 */
1031 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001032}
1033
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001034/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001035static int PARSER_FLAGS(PyCompilerFlags *flags)
1036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 int parser_flags = 0;
1038 if (!flags)
1039 return 0;
1040 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1041 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1042 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1043 parser_flags |= PyPARSE_IGNORE_COOKIE;
1044 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1045 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1046 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001047}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001048
Thomas Wouters89f507f2006-12-13 04:49:30 +00001049#if 0
1050/* Keep an example of flags with future keyword support. */
1051#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1053 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1054 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1055 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001056#endif
1057
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001058int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001059PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 PyObject *m, *d, *v, *w, *oenc = NULL;
1062 mod_ty mod;
1063 PyArena *arena;
1064 char *ps1 = "", *ps2 = "", *enc = NULL;
1065 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 if (fp == stdin) {
1068 /* Fetch encoding from sys.stdin */
1069 v = PySys_GetObject("stdin");
1070 if (v == NULL || v == Py_None)
1071 return -1;
1072 oenc = PyObject_GetAttrString(v, "encoding");
1073 if (!oenc)
1074 return -1;
1075 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001076 if (enc == NULL)
1077 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 }
1079 v = PySys_GetObject("ps1");
1080 if (v != NULL) {
1081 v = PyObject_Str(v);
1082 if (v == NULL)
1083 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001084 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001086 if (ps1 == NULL) {
1087 PyErr_Clear();
1088 ps1 = "";
1089 }
1090 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 }
1092 w = PySys_GetObject("ps2");
1093 if (w != NULL) {
1094 w = PyObject_Str(w);
1095 if (w == NULL)
1096 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001097 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001099 if (ps2 == NULL) {
1100 PyErr_Clear();
1101 ps2 = "";
1102 }
1103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 }
1105 arena = PyArena_New();
1106 if (arena == NULL) {
1107 Py_XDECREF(v);
1108 Py_XDECREF(w);
1109 Py_XDECREF(oenc);
1110 return -1;
1111 }
1112 mod = PyParser_ASTFromFile(fp, filename, enc,
1113 Py_single_input, ps1, ps2,
1114 flags, &errcode, arena);
1115 Py_XDECREF(v);
1116 Py_XDECREF(w);
1117 Py_XDECREF(oenc);
1118 if (mod == NULL) {
1119 PyArena_Free(arena);
1120 if (errcode == E_EOF) {
1121 PyErr_Clear();
1122 return E_EOF;
1123 }
1124 PyErr_Print();
1125 return -1;
1126 }
1127 m = PyImport_AddModule("__main__");
1128 if (m == NULL) {
1129 PyArena_Free(arena);
1130 return -1;
1131 }
1132 d = PyModule_GetDict(m);
1133 v = run_mod(mod, filename, d, d, flags, arena);
1134 PyArena_Free(arena);
1135 flush_io();
1136 if (v == NULL) {
1137 PyErr_Print();
1138 return -1;
1139 }
1140 Py_DECREF(v);
1141 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001142}
1143
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001144/* Check whether a file maybe a pyc file: Look at the extension,
1145 the file type, and, if we may close it, at the first few bytes. */
1146
1147static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001148maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1151 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 /* Only look into the file if we are allowed to close it, since
1154 it then should also be seekable. */
1155 if (closeit) {
1156 /* Read only two bytes of the magic. If the file was opened in
1157 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1158 be read as they are on disk. */
1159 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1160 unsigned char buf[2];
1161 /* Mess: In case of -x, the stream is NOT at its start now,
1162 and ungetc() was used to push back the first newline,
1163 which makes the current stream position formally undefined,
1164 and a x-platform nightmare.
1165 Unfortunately, we have no direct way to know whether -x
1166 was specified. So we use a terrible hack: if the current
1167 stream position is not 0, we assume -x was specified, and
1168 give up. Bug 132850 on SourceForge spells out the
1169 hopelessness of trying anything else (fseek and ftell
1170 don't work predictably x-platform for text-mode files).
1171 */
1172 int ispyc = 0;
1173 if (ftell(fp) == 0) {
1174 if (fread(buf, 1, 2, fp) == 2 &&
1175 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1176 ispyc = 1;
1177 rewind(fp);
1178 }
1179 return ispyc;
1180 }
1181 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001182}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001183
Guido van Rossum0df002c2000-08-27 19:21:52 +00001184int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001185PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 PyObject *m, *d, *v;
1189 const char *ext;
1190 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 m = PyImport_AddModule("__main__");
1193 if (m == NULL)
1194 return -1;
1195 d = PyModule_GetDict(m);
1196 if (PyDict_GetItemString(d, "__file__") == NULL) {
1197 PyObject *f;
Victor Stinner0fe25a42010-06-17 23:08:50 +00001198 f = PyUnicode_FromString(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 if (f == NULL)
1200 return -1;
1201 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1202 Py_DECREF(f);
1203 return -1;
1204 }
1205 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1206 return -1;
1207 set_file_name = 1;
1208 Py_DECREF(f);
1209 }
1210 len = strlen(filename);
1211 ext = filename + len - (len > 4 ? 4 : 0);
1212 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1213 /* Try to run a pyc file. First, re-open in binary */
1214 if (closeit)
1215 fclose(fp);
1216 if ((fp = fopen(filename, "rb")) == NULL) {
1217 fprintf(stderr, "python: Can't reopen .pyc file\n");
1218 ret = -1;
1219 goto done;
1220 }
1221 /* Turn on optimization if a .pyo file is given */
1222 if (strcmp(ext, ".pyo") == 0)
1223 Py_OptimizeFlag = 1;
1224 v = run_pyc_file(fp, filename, d, d, flags);
1225 } else {
1226 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1227 closeit, flags);
1228 }
1229 flush_io();
1230 if (v == NULL) {
1231 PyErr_Print();
1232 ret = -1;
1233 goto done;
1234 }
1235 Py_DECREF(v);
1236 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001237 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1239 PyErr_Clear();
1240 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001241}
1242
1243int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001244PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 PyObject *m, *d, *v;
1247 m = PyImport_AddModule("__main__");
1248 if (m == NULL)
1249 return -1;
1250 d = PyModule_GetDict(m);
1251 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1252 if (v == NULL) {
1253 PyErr_Print();
1254 return -1;
1255 }
1256 Py_DECREF(v);
1257 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001258}
1259
Barry Warsaw035574d1997-08-29 22:07:17 +00001260static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001261parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 long hold;
1265 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 /* old style errors */
1268 if (PyTuple_Check(err))
1269 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1270 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 if (! (v = PyObject_GetAttrString(err, "msg")))
1275 goto finally;
1276 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (!(v = PyObject_GetAttrString(err, "filename")))
1279 goto finally;
1280 if (v == Py_None)
1281 *filename = NULL;
1282 else if (! (*filename = _PyUnicode_AsString(v)))
1283 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 Py_DECREF(v);
1286 if (!(v = PyObject_GetAttrString(err, "lineno")))
1287 goto finally;
1288 hold = PyLong_AsLong(v);
1289 Py_DECREF(v);
1290 v = NULL;
1291 if (hold < 0 && PyErr_Occurred())
1292 goto finally;
1293 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (!(v = PyObject_GetAttrString(err, "offset")))
1296 goto finally;
1297 if (v == Py_None) {
1298 *offset = -1;
1299 Py_DECREF(v);
1300 v = NULL;
1301 } else {
1302 hold = PyLong_AsLong(v);
1303 Py_DECREF(v);
1304 v = NULL;
1305 if (hold < 0 && PyErr_Occurred())
1306 goto finally;
1307 *offset = (int)hold;
1308 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 if (!(v = PyObject_GetAttrString(err, "text")))
1311 goto finally;
1312 if (v == Py_None)
1313 *text = NULL;
1314 else if (!PyUnicode_Check(v) ||
1315 !(*text = _PyUnicode_AsString(v)))
1316 goto finally;
1317 Py_DECREF(v);
1318 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001319
1320finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 Py_XDECREF(v);
1322 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001323}
1324
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001325void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001326PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001329}
1330
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001331static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001332print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 char *nl;
1335 if (offset >= 0) {
1336 if (offset > 0 && offset == (int)strlen(text))
1337 offset--;
1338 for (;;) {
1339 nl = strchr(text, '\n');
1340 if (nl == NULL || nl-text >= offset)
1341 break;
1342 offset -= (int)(nl+1-text);
1343 text = nl+1;
1344 }
1345 while (*text == ' ' || *text == '\t') {
1346 text++;
1347 offset--;
1348 }
1349 }
1350 PyFile_WriteString(" ", f);
1351 PyFile_WriteString(text, f);
1352 if (*text == '\0' || text[strlen(text)-1] != '\n')
1353 PyFile_WriteString("\n", f);
1354 if (offset == -1)
1355 return;
1356 PyFile_WriteString(" ", f);
1357 offset--;
1358 while (offset > 0) {
1359 PyFile_WriteString(" ", f);
1360 offset--;
1361 }
1362 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001363}
1364
Guido van Rossum66e8e862001-03-23 17:54:43 +00001365static void
1366handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 PyObject *exception, *value, *tb;
1369 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 if (Py_InspectFlag)
1372 /* Don't exit if -i flag was given. This flag is set to 0
1373 * when entering interactive mode for inspecting. */
1374 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 PyErr_Fetch(&exception, &value, &tb);
1377 fflush(stdout);
1378 if (value == NULL || value == Py_None)
1379 goto done;
1380 if (PyExceptionInstance_Check(value)) {
1381 /* The error code should be in the `code' attribute. */
1382 PyObject *code = PyObject_GetAttrString(value, "code");
1383 if (code) {
1384 Py_DECREF(value);
1385 value = code;
1386 if (value == Py_None)
1387 goto done;
1388 }
1389 /* If we failed to dig out the 'code' attribute,
1390 just let the else clause below print the error. */
1391 }
1392 if (PyLong_Check(value))
1393 exitcode = (int)PyLong_AsLong(value);
1394 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001395 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001396 if (sys_stderr != NULL && sys_stderr != Py_None) {
1397 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1398 } else {
1399 PyObject_Print(value, stderr, Py_PRINT_RAW);
1400 fflush(stderr);
1401 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 PySys_WriteStderr("\n");
1403 exitcode = 1;
1404 }
Tim Peterscf615b52003-04-19 18:47:02 +00001405 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 /* Restore and clear the exception info, in order to properly decref
1407 * the exception, value, and traceback. If we just exit instead,
1408 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1409 * some finalizers from running.
1410 */
1411 PyErr_Restore(exception, value, tb);
1412 PyErr_Clear();
1413 Py_Exit(exitcode);
1414 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001415}
1416
1417void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001418PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1423 handle_system_exit();
1424 }
1425 PyErr_Fetch(&exception, &v, &tb);
1426 if (exception == NULL)
1427 return;
1428 PyErr_NormalizeException(&exception, &v, &tb);
1429 if (tb == NULL) {
1430 tb = Py_None;
1431 Py_INCREF(tb);
1432 }
1433 PyException_SetTraceback(v, tb);
1434 if (exception == NULL)
1435 return;
1436 /* Now we know v != NULL too */
1437 if (set_sys_last_vars) {
1438 PySys_SetObject("last_type", exception);
1439 PySys_SetObject("last_value", v);
1440 PySys_SetObject("last_traceback", tb);
1441 }
1442 hook = PySys_GetObject("excepthook");
1443 if (hook) {
1444 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1445 PyObject *result = PyEval_CallObject(hook, args);
1446 if (result == NULL) {
1447 PyObject *exception2, *v2, *tb2;
1448 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1449 handle_system_exit();
1450 }
1451 PyErr_Fetch(&exception2, &v2, &tb2);
1452 PyErr_NormalizeException(&exception2, &v2, &tb2);
1453 /* It should not be possible for exception2 or v2
1454 to be NULL. However PyErr_Display() can't
1455 tolerate NULLs, so just be safe. */
1456 if (exception2 == NULL) {
1457 exception2 = Py_None;
1458 Py_INCREF(exception2);
1459 }
1460 if (v2 == NULL) {
1461 v2 = Py_None;
1462 Py_INCREF(v2);
1463 }
1464 fflush(stdout);
1465 PySys_WriteStderr("Error in sys.excepthook:\n");
1466 PyErr_Display(exception2, v2, tb2);
1467 PySys_WriteStderr("\nOriginal exception was:\n");
1468 PyErr_Display(exception, v, tb);
1469 Py_DECREF(exception2);
1470 Py_DECREF(v2);
1471 Py_XDECREF(tb2);
1472 }
1473 Py_XDECREF(result);
1474 Py_XDECREF(args);
1475 } else {
1476 PySys_WriteStderr("sys.excepthook is missing\n");
1477 PyErr_Display(exception, v, tb);
1478 }
1479 Py_XDECREF(exception);
1480 Py_XDECREF(v);
1481 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001482}
1483
Benjamin Petersone6528212008-07-15 15:32:09 +00001484static void
1485print_exception(PyObject *f, PyObject *value)
1486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 int err = 0;
1488 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (!PyExceptionInstance_Check(value)) {
1491 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1492 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1493 PyFile_WriteString(" found\n", f);
1494 return;
1495 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 Py_INCREF(value);
1498 fflush(stdout);
1499 type = (PyObject *) Py_TYPE(value);
1500 tb = PyException_GetTraceback(value);
1501 if (tb && tb != Py_None)
1502 err = PyTraceBack_Print(tb, f);
1503 if (err == 0 &&
1504 PyObject_HasAttrString(value, "print_file_and_line"))
1505 {
1506 PyObject *message;
1507 const char *filename, *text;
1508 int lineno, offset;
1509 if (!parse_syntax_error(value, &message, &filename,
1510 &lineno, &offset, &text))
1511 PyErr_Clear();
1512 else {
1513 char buf[10];
1514 PyFile_WriteString(" File \"", f);
1515 if (filename == NULL)
1516 PyFile_WriteString("<string>", f);
1517 else
1518 PyFile_WriteString(filename, f);
1519 PyFile_WriteString("\", line ", f);
1520 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1521 PyFile_WriteString(buf, f);
1522 PyFile_WriteString("\n", f);
1523 if (text != NULL)
1524 print_error_text(f, offset, text);
1525 Py_DECREF(value);
1526 value = message;
1527 /* Can't be bothered to check all those
1528 PyFile_WriteString() calls */
1529 if (PyErr_Occurred())
1530 err = -1;
1531 }
1532 }
1533 if (err) {
1534 /* Don't do anything else */
1535 }
1536 else {
1537 PyObject* moduleName;
1538 char* className;
1539 assert(PyExceptionClass_Check(type));
1540 className = PyExceptionClass_Name(type);
1541 if (className != NULL) {
1542 char *dot = strrchr(className, '.');
1543 if (dot != NULL)
1544 className = dot+1;
1545 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 moduleName = PyObject_GetAttrString(type, "__module__");
1548 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1549 {
1550 Py_DECREF(moduleName);
1551 err = PyFile_WriteString("<unknown>", f);
1552 }
1553 else {
1554 char* modstr = _PyUnicode_AsString(moduleName);
1555 if (modstr && strcmp(modstr, "builtins"))
1556 {
1557 err = PyFile_WriteString(modstr, f);
1558 err += PyFile_WriteString(".", f);
1559 }
1560 Py_DECREF(moduleName);
1561 }
1562 if (err == 0) {
1563 if (className == NULL)
1564 err = PyFile_WriteString("<unknown>", f);
1565 else
1566 err = PyFile_WriteString(className, f);
1567 }
1568 }
1569 if (err == 0 && (value != Py_None)) {
1570 PyObject *s = PyObject_Str(value);
1571 /* only print colon if the str() of the
1572 object is not the empty string
1573 */
1574 if (s == NULL)
1575 err = -1;
1576 else if (!PyUnicode_Check(s) ||
1577 PyUnicode_GetSize(s) != 0)
1578 err = PyFile_WriteString(": ", f);
1579 if (err == 0)
1580 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1581 Py_XDECREF(s);
1582 }
1583 /* try to write a newline in any case */
1584 err += PyFile_WriteString("\n", f);
1585 Py_XDECREF(tb);
1586 Py_DECREF(value);
1587 /* If an error happened here, don't show it.
1588 XXX This is wrong, but too many callers rely on this behavior. */
1589 if (err != 0)
1590 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001591}
1592
1593static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 "\nThe above exception was the direct cause "
1595 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001596
1597static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 "\nDuring handling of the above exception, "
1599 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001600
1601static void
1602print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 int err = 0, res;
1605 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (seen != NULL) {
1608 /* Exception chaining */
1609 if (PySet_Add(seen, value) == -1)
1610 PyErr_Clear();
1611 else if (PyExceptionInstance_Check(value)) {
1612 cause = PyException_GetCause(value);
1613 context = PyException_GetContext(value);
1614 if (cause) {
1615 res = PySet_Contains(seen, cause);
1616 if (res == -1)
1617 PyErr_Clear();
1618 if (res == 0) {
1619 print_exception_recursive(
1620 f, cause, seen);
1621 err |= PyFile_WriteString(
1622 cause_message, f);
1623 }
1624 }
1625 else if (context) {
1626 res = PySet_Contains(seen, context);
1627 if (res == -1)
1628 PyErr_Clear();
1629 if (res == 0) {
1630 print_exception_recursive(
1631 f, context, seen);
1632 err |= PyFile_WriteString(
1633 context_message, f);
1634 }
1635 }
1636 Py_XDECREF(context);
1637 Py_XDECREF(cause);
1638 }
1639 }
1640 print_exception(f, value);
1641 if (err != 0)
1642 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001643}
1644
Thomas Wouters477c8d52006-05-27 19:21:47 +00001645void
1646PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 PyObject *seen;
1649 PyObject *f = PySys_GetObject("stderr");
1650 if (f == Py_None) {
1651 /* pass */
1652 }
1653 else if (f == NULL) {
1654 _PyObject_Dump(value);
1655 fprintf(stderr, "lost sys.stderr\n");
1656 }
1657 else {
1658 /* We choose to ignore seen being possibly NULL, and report
1659 at least the main exception (it could be a MemoryError).
1660 */
1661 seen = PySet_New(NULL);
1662 if (seen == NULL)
1663 PyErr_Clear();
1664 print_exception_recursive(f, value, seen);
1665 Py_XDECREF(seen);
1666 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001667}
1668
Guido van Rossum82598051997-03-05 00:20:32 +00001669PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001670PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 PyObject *ret = NULL;
1674 mod_ty mod;
1675 PyArena *arena = PyArena_New();
1676 if (arena == NULL)
1677 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1680 if (mod != NULL)
1681 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1682 PyArena_Free(arena);
1683 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001684}
1685
1686PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001687PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 PyObject *ret;
1691 mod_ty mod;
1692 PyArena *arena = PyArena_New();
1693 if (arena == NULL)
1694 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1697 flags, NULL, arena);
1698 if (closeit)
1699 fclose(fp);
1700 if (mod == NULL) {
1701 PyArena_Free(arena);
1702 return NULL;
1703 }
1704 ret = run_mod(mod, filename, globals, locals, flags, arena);
1705 PyArena_Free(arena);
1706 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001707}
1708
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001709static void
1710flush_io(void)
1711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyObject *f, *r;
1713 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 /* Save the current exception */
1716 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 f = PySys_GetObject("stderr");
1719 if (f != NULL) {
1720 r = PyObject_CallMethod(f, "flush", "");
1721 if (r)
1722 Py_DECREF(r);
1723 else
1724 PyErr_Clear();
1725 }
1726 f = PySys_GetObject("stdout");
1727 if (f != NULL) {
1728 r = PyObject_CallMethod(f, "flush", "");
1729 if (r)
1730 Py_DECREF(r);
1731 else
1732 PyErr_Clear();
1733 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001736}
1737
Guido van Rossum82598051997-03-05 00:20:32 +00001738static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001739run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 PyCodeObject *co;
1743 PyObject *v;
1744 co = PyAST_Compile(mod, filename, flags, arena);
1745 if (co == NULL)
1746 return NULL;
1747 v = PyEval_EvalCode(co, globals, locals);
1748 Py_DECREF(co);
1749 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001750}
1751
Guido van Rossum82598051997-03-05 00:20:32 +00001752static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001753run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 PyCodeObject *co;
1757 PyObject *v;
1758 long magic;
1759 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 magic = PyMarshal_ReadLongFromFile(fp);
1762 if (magic != PyImport_GetMagicNumber()) {
1763 PyErr_SetString(PyExc_RuntimeError,
1764 "Bad magic number in .pyc file");
1765 return NULL;
1766 }
1767 (void) PyMarshal_ReadLongFromFile(fp);
1768 v = PyMarshal_ReadLastObjectFromFile(fp);
1769 fclose(fp);
1770 if (v == NULL || !PyCode_Check(v)) {
1771 Py_XDECREF(v);
1772 PyErr_SetString(PyExc_RuntimeError,
1773 "Bad code object in .pyc file");
1774 return NULL;
1775 }
1776 co = (PyCodeObject *)v;
1777 v = PyEval_EvalCode(co, globals, locals);
1778 if (v && flags)
1779 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1780 Py_DECREF(co);
1781 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001782}
1783
Guido van Rossum82598051997-03-05 00:20:32 +00001784PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001785Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 PyCodeObject *co;
1789 mod_ty mod;
1790 PyArena *arena = PyArena_New();
1791 if (arena == NULL)
1792 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1795 if (mod == NULL) {
1796 PyArena_Free(arena);
1797 return NULL;
1798 }
1799 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1800 PyObject *result = PyAST_mod2obj(mod);
1801 PyArena_Free(arena);
1802 return result;
1803 }
1804 co = PyAST_Compile(mod, filename, flags, arena);
1805 PyArena_Free(arena);
1806 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001807}
1808
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001809struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001810Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 struct symtable *st;
1813 mod_ty mod;
1814 PyCompilerFlags flags;
1815 PyArena *arena = PyArena_New();
1816 if (arena == NULL)
1817 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 flags.cf_flags = 0;
1820 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1821 if (mod == NULL) {
1822 PyArena_Free(arena);
1823 return NULL;
1824 }
1825 st = PySymtable_Build(mod, filename, 0);
1826 PyArena_Free(arena);
1827 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001828}
1829
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001830/* Preferred access to parser is through AST. */
1831mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001832PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 mod_ty mod;
1836 PyCompilerFlags localflags;
1837 perrdetail err;
1838 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1841 &_PyParser_Grammar, start, &err,
1842 &iflags);
1843 if (flags == NULL) {
1844 localflags.cf_flags = 0;
1845 flags = &localflags;
1846 }
1847 if (n) {
1848 flags->cf_flags |= iflags & PyCF_MASK;
1849 mod = PyAST_FromNode(n, flags, filename, arena);
1850 PyNode_Free(n);
1851 return mod;
1852 }
1853 else {
1854 err_input(&err);
1855 return NULL;
1856 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001857}
1858
1859mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001860PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 int start, char *ps1,
1862 char *ps2, PyCompilerFlags *flags, int *errcode,
1863 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 mod_ty mod;
1866 PyCompilerFlags localflags;
1867 perrdetail err;
1868 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1871 &_PyParser_Grammar,
1872 start, ps1, ps2, &err, &iflags);
1873 if (flags == NULL) {
1874 localflags.cf_flags = 0;
1875 flags = &localflags;
1876 }
1877 if (n) {
1878 flags->cf_flags |= iflags & PyCF_MASK;
1879 mod = PyAST_FromNode(n, flags, filename, arena);
1880 PyNode_Free(n);
1881 return mod;
1882 }
1883 else {
1884 err_input(&err);
1885 if (errcode)
1886 *errcode = err.error;
1887 return NULL;
1888 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889}
1890
Guido van Rossuma110aa61994-08-29 12:50:44 +00001891/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001892
Guido van Rossuma110aa61994-08-29 12:50:44 +00001893node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001894PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 perrdetail err;
1897 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1898 &_PyParser_Grammar,
1899 start, NULL, NULL, &err, flags);
1900 if (n == NULL)
1901 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001904}
1905
Guido van Rossuma110aa61994-08-29 12:50:44 +00001906/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001907
Guido van Rossuma110aa61994-08-29 12:50:44 +00001908node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001909PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 perrdetail err;
1912 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1913 start, &err, flags);
1914 if (n == NULL)
1915 err_input(&err);
1916 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001917}
1918
1919node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001920PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 perrdetail err;
1924 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1925 &_PyParser_Grammar, start, &err, flags);
1926 if (n == NULL)
1927 err_input(&err);
1928 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001929}
1930
1931node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001932PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001935}
1936
Guido van Rossum66ebd912003-04-17 16:02:26 +00001937/* May want to move a more generalized form of this to parsetok.c or
1938 even parser modules. */
1939
1940void
1941PyParser_SetError(perrdetail *err)
1942{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001944}
1945
Guido van Rossuma110aa61994-08-29 12:50:44 +00001946/* Set the error appropriate to the given input error code (see errcode.h) */
1947
1948static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001949err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 PyObject *v, *w, *errtype, *errtext;
1952 PyObject *msg_obj = NULL;
1953 char *msg = NULL;
1954 errtype = PyExc_SyntaxError;
1955 switch (err->error) {
1956 case E_ERROR:
1957 return;
1958 case E_SYNTAX:
1959 errtype = PyExc_IndentationError;
1960 if (err->expected == INDENT)
1961 msg = "expected an indented block";
1962 else if (err->token == INDENT)
1963 msg = "unexpected indent";
1964 else if (err->token == DEDENT)
1965 msg = "unexpected unindent";
1966 else {
1967 errtype = PyExc_SyntaxError;
1968 msg = "invalid syntax";
1969 }
1970 break;
1971 case E_TOKEN:
1972 msg = "invalid token";
1973 break;
1974 case E_EOFS:
1975 msg = "EOF while scanning triple-quoted string literal";
1976 break;
1977 case E_EOLS:
1978 msg = "EOL while scanning string literal";
1979 break;
1980 case E_INTR:
1981 if (!PyErr_Occurred())
1982 PyErr_SetNone(PyExc_KeyboardInterrupt);
1983 goto cleanup;
1984 case E_NOMEM:
1985 PyErr_NoMemory();
1986 goto cleanup;
1987 case E_EOF:
1988 msg = "unexpected EOF while parsing";
1989 break;
1990 case E_TABSPACE:
1991 errtype = PyExc_TabError;
1992 msg = "inconsistent use of tabs and spaces in indentation";
1993 break;
1994 case E_OVERFLOW:
1995 msg = "expression too long";
1996 break;
1997 case E_DEDENT:
1998 errtype = PyExc_IndentationError;
1999 msg = "unindent does not match any outer indentation level";
2000 break;
2001 case E_TOODEEP:
2002 errtype = PyExc_IndentationError;
2003 msg = "too many levels of indentation";
2004 break;
2005 case E_DECODE: {
2006 PyObject *type, *value, *tb;
2007 PyErr_Fetch(&type, &value, &tb);
2008 msg = "unknown decode error";
2009 if (value != NULL)
2010 msg_obj = PyObject_Str(value);
2011 Py_XDECREF(type);
2012 Py_XDECREF(value);
2013 Py_XDECREF(tb);
2014 break;
2015 }
2016 case E_LINECONT:
2017 msg = "unexpected character after line continuation character";
2018 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002019
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 case E_IDENTIFIER:
2021 msg = "invalid character in identifier";
2022 break;
2023 default:
2024 fprintf(stderr, "error=%d\n", err->error);
2025 msg = "unknown parsing error";
2026 break;
2027 }
2028 /* err->text may not be UTF-8 in case of decoding errors.
2029 Explicitly convert to an object. */
2030 if (!err->text) {
2031 errtext = Py_None;
2032 Py_INCREF(Py_None);
2033 } else {
2034 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2035 "replace");
2036 }
2037 v = Py_BuildValue("(ziiN)", err->filename,
2038 err->lineno, err->offset, errtext);
2039 if (v != NULL) {
2040 if (msg_obj)
2041 w = Py_BuildValue("(OO)", msg_obj, v);
2042 else
2043 w = Py_BuildValue("(sO)", msg, v);
2044 } else
2045 w = NULL;
2046 Py_XDECREF(v);
2047 PyErr_SetObject(errtype, w);
2048 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002049cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 Py_XDECREF(msg_obj);
2051 if (err->text != NULL) {
2052 PyObject_FREE(err->text);
2053 err->text = NULL;
2054 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002055}
2056
2057/* Print fatal error message and abort */
2058
2059void
Tim Peters7c321a82002-07-09 02:57:01 +00002060Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 fprintf(stderr, "Fatal Python error: %s\n", msg);
2063 fflush(stderr); /* it helps in Windows debug build */
2064 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002065 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002067#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 {
2069 size_t len = strlen(msg);
2070 WCHAR* buffer;
2071 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 /* Convert the message to wchar_t. This uses a simple one-to-one
2074 conversion, assuming that the this error message actually uses ASCII
2075 only. If this ceases to be true, we will have to convert. */
2076 buffer = alloca( (len+1) * (sizeof *buffer));
2077 for( i=0; i<=len; ++i)
2078 buffer[i] = msg[i];
2079 OutputDebugStringW(L"Fatal Python error: ");
2080 OutputDebugStringW(buffer);
2081 OutputDebugStringW(L"\n");
2082 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002083#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002085#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002086#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002088}
2089
2090/* Clean up and exit */
2091
Guido van Rossuma110aa61994-08-29 12:50:44 +00002092#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002093#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002094#endif
2095
Collin Winter670e6922007-03-21 02:57:17 +00002096static void (*pyexitfunc)(void) = NULL;
2097/* For the atexit module. */
2098void _Py_PyAtExit(void (*func)(void))
2099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002101}
2102
2103static void
2104call_py_exitfuncs(void)
2105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 if (pyexitfunc == NULL)
2107 return;
Collin Winter670e6922007-03-21 02:57:17 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 (*pyexitfunc)();
2110 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002111}
2112
Antoine Pitrou011bd622009-10-20 21:52:47 +00002113/* Wait until threading._shutdown completes, provided
2114 the threading module was imported in the first place.
2115 The shutdown routine will wait until all non-daemon
2116 "threading" threads have completed. */
2117static void
2118wait_for_thread_shutdown(void)
2119{
2120#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 PyObject *result;
2122 PyThreadState *tstate = PyThreadState_GET();
2123 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2124 "threading");
2125 if (threading == NULL) {
2126 /* threading not imported */
2127 PyErr_Clear();
2128 return;
2129 }
2130 result = PyObject_CallMethod(threading, "_shutdown", "");
2131 if (result == NULL) {
2132 PyErr_WriteUnraisable(threading);
2133 }
2134 else {
2135 Py_DECREF(result);
2136 }
2137 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002138#endif
2139}
2140
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002141#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002142static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002143static int nexitfuncs = 0;
2144
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002145int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 if (nexitfuncs >= NEXITFUNCS)
2148 return -1;
2149 exitfuncs[nexitfuncs++] = func;
2150 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002151}
2152
Guido van Rossumcc283f51997-08-05 02:22:03 +00002153static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002154call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 while (nexitfuncs > 0)
2157 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 fflush(stdout);
2160 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002161}
2162
2163void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002164Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002169}
2170
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002171static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002172initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002173{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002174#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002176#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002177#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002179#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002180#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002182#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002184}
2185
Guido van Rossum7433b121997-02-14 19:45:36 +00002186
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002187/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2188 *
2189 * All of the code in this function must only use async-signal-safe functions,
2190 * listed at `man 7 signal` or
2191 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2192 */
2193void
2194_Py_RestoreSignals(void)
2195{
2196#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002198#endif
2199#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002201#endif
2202#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002204#endif
2205}
2206
2207
Guido van Rossum7433b121997-02-14 19:45:36 +00002208/*
2209 * The file descriptor fd is considered ``interactive'' if either
2210 * a) isatty(fd) is TRUE, or
2211 * b) the -i flag was given, and the filename associated with
2212 * the descriptor is NULL or "<stdin>" or "???".
2213 */
2214int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002215Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 if (isatty((int)fileno(fp)))
2218 return 1;
2219 if (!Py_InteractiveFlag)
2220 return 0;
2221 return (filename == NULL) ||
2222 (strcmp(filename, "<stdin>") == 0) ||
2223 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002224}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002225
2226
Tim Petersd08e3822003-04-17 15:24:21 +00002227#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002228#if defined(WIN32) && defined(_MSC_VER)
2229
2230/* Stack checking for Microsoft C */
2231
2232#include <malloc.h>
2233#include <excpt.h>
2234
Fred Drakee8de31c2000-08-31 05:38:39 +00002235/*
2236 * Return non-zero when we run out of memory on the stack; zero otherwise.
2237 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002238int
Fred Drake399739f2000-08-31 05:52:44 +00002239PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 __try {
2242 /* alloca throws a stack overflow exception if there's
2243 not enough space left on the stack */
2244 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2245 return 0;
2246 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2247 EXCEPTION_EXECUTE_HANDLER :
2248 EXCEPTION_CONTINUE_SEARCH) {
2249 int errcode = _resetstkoflw();
2250 if (errcode == 0)
2251 {
2252 Py_FatalError("Could not reset the stack!");
2253 }
2254 }
2255 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002256}
2257
2258#endif /* WIN32 && _MSC_VER */
2259
2260/* Alternate implementations can be added here... */
2261
2262#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002263
2264
2265/* Wrappers around sigaction() or signal(). */
2266
2267PyOS_sighandler_t
2268PyOS_getsig(int sig)
2269{
2270#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 struct sigaction context;
2272 if (sigaction(sig, NULL, &context) == -1)
2273 return SIG_ERR;
2274 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002275#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002277/* Special signal handling for the secure CRT in Visual Studio 2005 */
2278#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 switch (sig) {
2280 /* Only these signals are valid */
2281 case SIGINT:
2282 case SIGILL:
2283 case SIGFPE:
2284 case SIGSEGV:
2285 case SIGTERM:
2286 case SIGBREAK:
2287 case SIGABRT:
2288 break;
2289 /* Don't call signal() with other values or it will assert */
2290 default:
2291 return SIG_ERR;
2292 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002293#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 handler = signal(sig, SIG_IGN);
2295 if (handler != SIG_ERR)
2296 signal(sig, handler);
2297 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002298#endif
2299}
2300
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002301/*
2302 * All of the code in this function must only use async-signal-safe functions,
2303 * listed at `man 7 signal` or
2304 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2305 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002306PyOS_sighandler_t
2307PyOS_setsig(int sig, PyOS_sighandler_t handler)
2308{
2309#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 /* Some code in Modules/signalmodule.c depends on sigaction() being
2311 * used here if HAVE_SIGACTION is defined. Fix that if this code
2312 * changes to invalidate that assumption.
2313 */
2314 struct sigaction context, ocontext;
2315 context.sa_handler = handler;
2316 sigemptyset(&context.sa_mask);
2317 context.sa_flags = 0;
2318 if (sigaction(sig, &context, &ocontext) == -1)
2319 return SIG_ERR;
2320 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002321#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 PyOS_sighandler_t oldhandler;
2323 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002324#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002326#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002328#endif
2329}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002330
2331/* Deprecated C API functions still provided for binary compatiblity */
2332
2333#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002334PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002338}
2339
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002340#undef PyParser_SimpleParseString
2341PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342PyParser_SimpleParseString(const char *str, int start)
2343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002345}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002346
2347#undef PyRun_AnyFile
2348PyAPI_FUNC(int)
2349PyRun_AnyFile(FILE *fp, const char *name)
2350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002352}
2353
2354#undef PyRun_AnyFileEx
2355PyAPI_FUNC(int)
2356PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002359}
2360
2361#undef PyRun_AnyFileFlags
2362PyAPI_FUNC(int)
2363PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002366}
2367
2368#undef PyRun_File
2369PyAPI_FUNC(PyObject *)
2370PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002373}
2374
2375#undef PyRun_FileEx
2376PyAPI_FUNC(PyObject *)
2377PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002380}
2381
2382#undef PyRun_FileFlags
2383PyAPI_FUNC(PyObject *)
2384PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002388}
2389
2390#undef PyRun_SimpleFile
2391PyAPI_FUNC(int)
2392PyRun_SimpleFile(FILE *f, const char *p)
2393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002395}
2396
2397#undef PyRun_SimpleFileEx
2398PyAPI_FUNC(int)
2399PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002402}
2403
2404
2405#undef PyRun_String
2406PyAPI_FUNC(PyObject *)
2407PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002410}
2411
2412#undef PyRun_SimpleString
2413PyAPI_FUNC(int)
2414PyRun_SimpleString(const char *s)
2415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002417}
2418
2419#undef Py_CompileString
2420PyAPI_FUNC(PyObject *)
2421Py_CompileString(const char *str, const char *p, int s)
2422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002424}
2425
2426#undef PyRun_InteractiveOne
2427PyAPI_FUNC(int)
2428PyRun_InteractiveOne(FILE *f, const char *p)
2429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002431}
2432
2433#undef PyRun_InteractiveLoop
2434PyAPI_FUNC(int)
2435PyRun_InteractiveLoop(FILE *f, const char *p)
2436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002438}
2439
2440#ifdef __cplusplus
2441}
2442#endif