blob: 233fc16ea136fac83d4152525da72e9ed11a3bcf [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
Guido van Rossume13ddc92003-04-17 17:29:22 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 /* Destroy all modules */
409 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 /* Flush stdout+stderr (again, in case more was printed) */
412 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 /* Collect final garbage. This disposes of cycles created by
415 * new-style class definitions, for example.
416 * XXX This is disabled because it caused too many problems. If
417 * XXX a __del__ or weakref callback triggers here, Python code has
418 * XXX a hard time running, because even the sys module has been
419 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
420 * XXX One symptom is a sequence of information-free messages
421 * XXX coming from threads (if a __del__ or callback is invoked,
422 * XXX other threads can execute too, and any exception they encounter
423 * XXX triggers a comedy of errors as subsystem after subsystem
424 * XXX fails to find what it *expects* to find in sys to help report
425 * XXX the exception and consequent unexpected failures). I've also
426 * XXX seen segfaults then, after adding print statements to the
427 * XXX Python code getting called.
428 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000429#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000431#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
434 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000437#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000439#endif
440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000442
Tim Peters9cf25ce2003-04-17 15:21:01 +0000443#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 /* Display all objects still alive -- this can invoke arbitrary
445 * __repr__ overrides, so requires a mostly-intact interpreter.
446 * Alas, a lot of stuff may still be alive now that will be cleaned
447 * up later.
448 */
449 if (Py_GETENV("PYTHONDUMPREFS"))
450 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000451#endif /* Py_TRACE_REFS */
452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* Clear interpreter state */
454 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 /* Now we decref the exception classes. After this point nothing
457 can raise an exception. That's okay, because each Fini() method
458 below has been checked to make sure no exceptions are ever
459 raised.
460 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000465#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000467#endif /* WITH_THREAD */
468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 /* Delete current thread */
470 PyThreadState_Swap(NULL);
471 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 /* Sundry finalizers */
474 PyMethod_Fini();
475 PyFrame_Fini();
476 PyCFunction_Fini();
477 PyTuple_Fini();
478 PyList_Fini();
479 PySet_Fini();
480 PyBytes_Fini();
481 PyByteArray_Fini();
482 PyLong_Fini();
483 PyFloat_Fini();
484 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 /* Cleanup Unicode implementation */
487 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000490 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 free((char*)Py_FileSystemDefaultEncoding);
492 Py_FileSystemDefaultEncoding = NULL;
493 }
Christian Heimesc8967002007-11-30 10:18:26 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* XXX Still allocated:
496 - various static ad-hoc pointers to interned strings
497 - int and float free list blocks
498 - whatever various modules and libraries allocate
499 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000502
Tim Peters269b2a62003-04-17 19:52:29 +0000503#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 /* Display addresses (& refcnts) of all objects still alive.
505 * An address can be used to find the repr of the object, printed
506 * above by _Py_PrintReferences.
507 */
508 if (Py_GETENV("PYTHONDUMPREFS"))
509 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000510#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000511#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (Py_GETENV("PYTHONMALLOCSTATS"))
513 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000514#endif
515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000517}
518
519/* Create and initialize a new interpreter and thread, and return the
520 new thread. This requires that Py_Initialize() has been called
521 first.
522
523 Unsuccessful initialization yields a NULL pointer. Note that *no*
524 exception information is available even in this case -- the
525 exception information is held in the thread, and there is no
526 thread.
527
528 Locking: as above.
529
530*/
531
532PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000533Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 PyInterpreterState *interp;
536 PyThreadState *tstate, *save_tstate;
537 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 if (!initialized)
540 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 interp = PyInterpreterState_New();
543 if (interp == NULL)
544 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 tstate = PyThreadState_New(interp);
547 if (tstate == NULL) {
548 PyInterpreterState_Delete(interp);
549 return NULL;
550 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 interp->modules = PyDict_New();
557 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 bimod = _PyImport_FindExtension("builtins", "builtins");
560 if (bimod != NULL) {
561 interp->builtins = PyModule_GetDict(bimod);
562 if (interp->builtins == NULL)
563 goto handle_error;
564 Py_INCREF(interp->builtins);
565 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 /* initialize builtin exceptions */
568 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 sysmod = _PyImport_FindExtension("sys", "sys");
571 if (bimod != NULL && sysmod != NULL) {
572 PyObject *pstderr;
573 interp->sysdict = PyModule_GetDict(sysmod);
574 if (interp->sysdict == NULL)
575 goto handle_error;
576 Py_INCREF(interp->sysdict);
577 PySys_SetPath(Py_GetPath());
578 PyDict_SetItemString(interp->sysdict, "modules",
579 interp->modules);
580 /* Set up a preliminary stderr printer until we have enough
581 infrastructure for the io module in place. */
582 pstderr = PyFile_NewStdPrinter(fileno(stderr));
583 if (pstderr == NULL)
584 Py_FatalError("Py_Initialize: can't set preliminary stderr");
585 PySys_SetObject("stderr", pstderr);
586 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 _PyImportHooks_Init();
589 if (initstdio() < 0)
590 Py_FatalError(
591 "Py_Initialize: can't initialize sys standard streams");
592 initmain();
593 if (!Py_NoSiteFlag)
594 initsite();
595 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 if (!PyErr_Occurred())
598 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000599
Thomas Wouters89f507f2006-12-13 04:49:30 +0000600handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 PyErr_Print();
604 PyThreadState_Clear(tstate);
605 PyThreadState_Swap(save_tstate);
606 PyThreadState_Delete(tstate);
607 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610}
611
612/* Delete an interpreter and its last thread. This requires that the
613 given thread state is current, that the thread has no remaining
614 frames, and that it is its interpreter's only remaining thread.
615 It is a fatal error to violate these constraints.
616
617 (Py_Finalize() doesn't have these constraints -- it zaps
618 everything, regardless.)
619
620 Locking: as above.
621
622*/
623
624void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000625Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (tstate != PyThreadState_GET())
630 Py_FatalError("Py_EndInterpreter: thread is not current");
631 if (tstate->frame != NULL)
632 Py_FatalError("Py_EndInterpreter: thread still has a frame");
633 if (tstate != interp->tstate_head || tstate->next != NULL)
634 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 PyImport_Cleanup();
637 PyInterpreterState_Clear(interp);
638 PyThreadState_Swap(NULL);
639 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000640}
641
Martin v. Löwis790465f2008-04-05 20:41:37 +0000642static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000643
644void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000645Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (pn && *pn)
648 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000649}
650
Martin v. Löwis790465f2008-04-05 20:41:37 +0000651wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000652Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000655}
656
Martin v. Löwis790465f2008-04-05 20:41:37 +0000657static wchar_t *default_home = NULL;
658static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000659
660void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000661Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000664}
665
Martin v. Löwis790465f2008-04-05 20:41:37 +0000666wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000667Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 wchar_t *home = default_home;
670 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
671 char* chome = Py_GETENV("PYTHONHOME");
672 if (chome) {
673 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
674 if (r != (size_t)-1 && r <= PATH_MAX)
675 home = env_home;
676 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 }
679 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000680}
681
Guido van Rossum6135a871995-01-09 17:53:26 +0000682/* Create __main__ module */
683
684static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000685initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyObject *m, *d;
688 m = PyImport_AddModule("__main__");
689 if (m == NULL)
690 Py_FatalError("can't create __main__ module");
691 d = PyModule_GetDict(m);
692 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
693 PyObject *bimod = PyImport_ImportModule("builtins");
694 if (bimod == NULL ||
695 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
696 Py_FatalError("can't add __builtins__ to __main__");
697 Py_DECREF(bimod);
698 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000699}
700
Victor Stinnerb744ba12010-05-15 12:27:16 +0000701static void
702initfsencoding(void)
703{
704 PyObject *codec;
705#if defined(HAVE_LANGINFO_H) && defined(CODESET)
706 char *codeset;
707
Victor Stinner7f84ab52010-06-11 00:36:33 +0000708 if (Py_FileSystemDefaultEncoding == NULL) {
709 /* On Unix, set the file system encoding according to the
710 user's preference, if the CODESET names a well-known
711 Python codec, and Py_FileSystemDefaultEncoding isn't
712 initialized by other means. Also set the encoding of
713 stdin and stdout if these are terminals. */
714 codeset = get_codeset();
715 if (codeset != NULL) {
716 Py_FileSystemDefaultEncoding = codeset;
717 Py_HasFileSystemDefaultEncoding = 0;
718 return;
719 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000720
Victor Stinner7f84ab52010-06-11 00:36:33 +0000721 PyErr_Clear();
722 fprintf(stderr,
723 "Unable to get the locale encoding: "
724 "fallback to utf-8\n");
725 Py_FileSystemDefaultEncoding = "utf-8";
726 Py_HasFileSystemDefaultEncoding = 1;
727 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000728#endif
729
730 /* the encoding is mbcs, utf-8 or ascii */
731 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
732 if (!codec) {
733 /* Such error can only occurs in critical situations: no more
734 * memory, import a module of the standard library failed,
735 * etc. */
736 Py_FatalError("Py_Initialize: unable to load the file system codec");
737 } else {
738 Py_DECREF(codec);
739 }
740}
741
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000742/* Import the site module (not into __main__ though) */
743
744static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000745initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyObject *m;
748 m = PyImport_ImportModule("site");
749 if (m == NULL) {
750 PyErr_Print();
751 Py_Finalize();
752 exit(1);
753 }
754 else {
755 Py_DECREF(m);
756 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000757}
758
Antoine Pitrou05608432009-01-09 18:53:14 +0000759static PyObject*
760create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 int fd, int write_mode, char* name,
762 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
765 const char* mode;
766 PyObject *line_buffering;
767 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 /* stdin is always opened in buffered mode, first because it shouldn't
770 make a difference in common use cases, second because TextIOWrapper
771 depends on the presence of a read1() method which only exists on
772 buffered streams.
773 */
774 if (Py_UnbufferedStdioFlag && write_mode)
775 buffering = 0;
776 else
777 buffering = -1;
778 if (write_mode)
779 mode = "wb";
780 else
781 mode = "rb";
782 buf = PyObject_CallMethod(io, "open", "isiOOOi",
783 fd, mode, buffering,
784 Py_None, Py_None, Py_None, 0);
785 if (buf == NULL)
786 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 if (buffering) {
789 raw = PyObject_GetAttrString(buf, "raw");
790 if (raw == NULL)
791 goto error;
792 }
793 else {
794 raw = buf;
795 Py_INCREF(raw);
796 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 text = PyUnicode_FromString(name);
799 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
800 goto error;
801 res = PyObject_CallMethod(raw, "isatty", "");
802 if (res == NULL)
803 goto error;
804 isatty = PyObject_IsTrue(res);
805 Py_DECREF(res);
806 if (isatty == -1)
807 goto error;
808 if (isatty || Py_UnbufferedStdioFlag)
809 line_buffering = Py_True;
810 else
811 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 Py_CLEAR(raw);
814 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
817 buf, encoding, errors,
818 "\n", line_buffering);
819 Py_CLEAR(buf);
820 if (stream == NULL)
821 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (write_mode)
824 mode = "w";
825 else
826 mode = "r";
827 text = PyUnicode_FromString(mode);
828 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
829 goto error;
830 Py_CLEAR(text);
831 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000832
833error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 Py_XDECREF(buf);
835 Py_XDECREF(stream);
836 Py_XDECREF(text);
837 Py_XDECREF(raw);
838 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000839}
840
Georg Brandl1a3284e2007-12-02 09:40:06 +0000841/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000842static int
843initstdio(void)
844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyObject *iomod = NULL, *wrapper;
846 PyObject *bimod = NULL;
847 PyObject *m;
848 PyObject *std = NULL;
849 int status = 0, fd;
850 PyObject * encoding_attr;
851 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 /* Hack to avoid a nasty recursion issue when Python is invoked
854 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
855 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
856 goto error;
857 }
858 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
861 goto error;
862 }
863 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 if (!(bimod = PyImport_ImportModule("builtins"))) {
866 goto error;
867 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 if (!(iomod = PyImport_ImportModule("io"))) {
870 goto error;
871 }
872 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
873 goto error;
874 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 /* Set builtins.open */
877 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
878 goto error;
879 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 encoding = Py_GETENV("PYTHONIOENCODING");
882 errors = NULL;
883 if (encoding) {
884 encoding = strdup(encoding);
885 errors = strchr(encoding, ':');
886 if (errors) {
887 *errors = '\0';
888 errors++;
889 }
890 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 /* Set sys.stdin */
893 fd = fileno(stdin);
894 /* Under some conditions stdin, stdout and stderr may not be connected
895 * and fileno() may point to an invalid file descriptor. For example
896 * GUI apps don't have valid standard streams by default.
897 */
898 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000899#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 std = Py_None;
901 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000902#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000904#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 }
906 else {
907 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
908 if (std == NULL)
909 goto error;
910 } /* if (fd < 0) */
911 PySys_SetObject("__stdin__", std);
912 PySys_SetObject("stdin", std);
913 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* Set sys.stdout */
916 fd = fileno(stdout);
917 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000918#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 std = Py_None;
920 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000921#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000923#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 }
925 else {
926 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
927 if (std == NULL)
928 goto error;
929 } /* if (fd < 0) */
930 PySys_SetObject("__stdout__", std);
931 PySys_SetObject("stdout", std);
932 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000933
Guido van Rossum98297ee2007-11-06 21:34:58 +0000934#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 /* Set sys.stderr, replaces the preliminary stderr */
936 fd = fileno(stderr);
937 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000938#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 std = Py_None;
940 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000941#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000943#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 }
945 else {
946 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
947 if (std == NULL)
948 goto error;
949 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 /* Same as hack above, pre-import stderr's codec to avoid recursion
952 when import.c tries to write to stderr in verbose mode. */
953 encoding_attr = PyObject_GetAttrString(std, "encoding");
954 if (encoding_attr != NULL) {
955 const char * encoding;
956 encoding = _PyUnicode_AsString(encoding_attr);
957 if (encoding != NULL) {
958 _PyCodec_Lookup(encoding);
959 }
960 }
961 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 PySys_SetObject("__stderr__", std);
964 PySys_SetObject("stderr", std);
965 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000966#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000969 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 status = -1;
971 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 if (encoding)
974 free(encoding);
975 Py_XDECREF(bimod);
976 Py_XDECREF(iomod);
977 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000978}
979
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000980/* Parse input from a file and execute it */
981
982int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000983PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (filename == NULL)
987 filename = "???";
988 if (Py_FdIsInteractive(fp, filename)) {
989 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
990 if (closeit)
991 fclose(fp);
992 return err;
993 }
994 else
995 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000996}
997
998int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000999PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 PyObject *v;
1002 int ret;
1003 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (flags == NULL) {
1006 flags = &local_flags;
1007 local_flags.cf_flags = 0;
1008 }
1009 v = PySys_GetObject("ps1");
1010 if (v == NULL) {
1011 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1012 Py_XDECREF(v);
1013 }
1014 v = PySys_GetObject("ps2");
1015 if (v == NULL) {
1016 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1017 Py_XDECREF(v);
1018 }
1019 for (;;) {
1020 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1021 PRINT_TOTAL_REFS();
1022 if (ret == E_EOF)
1023 return 0;
1024 /*
1025 if (ret == E_NOMEM)
1026 return -1;
1027 */
1028 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001029}
1030
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001031/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001032static int PARSER_FLAGS(PyCompilerFlags *flags)
1033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 int parser_flags = 0;
1035 if (!flags)
1036 return 0;
1037 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1038 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1039 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1040 parser_flags |= PyPARSE_IGNORE_COOKIE;
1041 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1042 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1043 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001044}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001045
Thomas Wouters89f507f2006-12-13 04:49:30 +00001046#if 0
1047/* Keep an example of flags with future keyword support. */
1048#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1050 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1051 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1052 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001053#endif
1054
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001055int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001056PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 PyObject *m, *d, *v, *w, *oenc = NULL;
1059 mod_ty mod;
1060 PyArena *arena;
1061 char *ps1 = "", *ps2 = "", *enc = NULL;
1062 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 if (fp == stdin) {
1065 /* Fetch encoding from sys.stdin */
1066 v = PySys_GetObject("stdin");
1067 if (v == NULL || v == Py_None)
1068 return -1;
1069 oenc = PyObject_GetAttrString(v, "encoding");
1070 if (!oenc)
1071 return -1;
1072 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001073 if (enc == NULL)
1074 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 }
1076 v = PySys_GetObject("ps1");
1077 if (v != NULL) {
1078 v = PyObject_Str(v);
1079 if (v == NULL)
1080 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001081 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001083 if (ps1 == NULL) {
1084 PyErr_Clear();
1085 ps1 = "";
1086 }
1087 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 }
1089 w = PySys_GetObject("ps2");
1090 if (w != NULL) {
1091 w = PyObject_Str(w);
1092 if (w == NULL)
1093 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001094 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001096 if (ps2 == NULL) {
1097 PyErr_Clear();
1098 ps2 = "";
1099 }
1100 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 }
1102 arena = PyArena_New();
1103 if (arena == NULL) {
1104 Py_XDECREF(v);
1105 Py_XDECREF(w);
1106 Py_XDECREF(oenc);
1107 return -1;
1108 }
1109 mod = PyParser_ASTFromFile(fp, filename, enc,
1110 Py_single_input, ps1, ps2,
1111 flags, &errcode, arena);
1112 Py_XDECREF(v);
1113 Py_XDECREF(w);
1114 Py_XDECREF(oenc);
1115 if (mod == NULL) {
1116 PyArena_Free(arena);
1117 if (errcode == E_EOF) {
1118 PyErr_Clear();
1119 return E_EOF;
1120 }
1121 PyErr_Print();
1122 return -1;
1123 }
1124 m = PyImport_AddModule("__main__");
1125 if (m == NULL) {
1126 PyArena_Free(arena);
1127 return -1;
1128 }
1129 d = PyModule_GetDict(m);
1130 v = run_mod(mod, filename, d, d, flags, arena);
1131 PyArena_Free(arena);
1132 flush_io();
1133 if (v == NULL) {
1134 PyErr_Print();
1135 return -1;
1136 }
1137 Py_DECREF(v);
1138 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001139}
1140
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001141/* Check whether a file maybe a pyc file: Look at the extension,
1142 the file type, and, if we may close it, at the first few bytes. */
1143
1144static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001145maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1148 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 /* Only look into the file if we are allowed to close it, since
1151 it then should also be seekable. */
1152 if (closeit) {
1153 /* Read only two bytes of the magic. If the file was opened in
1154 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1155 be read as they are on disk. */
1156 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1157 unsigned char buf[2];
1158 /* Mess: In case of -x, the stream is NOT at its start now,
1159 and ungetc() was used to push back the first newline,
1160 which makes the current stream position formally undefined,
1161 and a x-platform nightmare.
1162 Unfortunately, we have no direct way to know whether -x
1163 was specified. So we use a terrible hack: if the current
1164 stream position is not 0, we assume -x was specified, and
1165 give up. Bug 132850 on SourceForge spells out the
1166 hopelessness of trying anything else (fseek and ftell
1167 don't work predictably x-platform for text-mode files).
1168 */
1169 int ispyc = 0;
1170 if (ftell(fp) == 0) {
1171 if (fread(buf, 1, 2, fp) == 2 &&
1172 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1173 ispyc = 1;
1174 rewind(fp);
1175 }
1176 return ispyc;
1177 }
1178 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001179}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001180
Guido van Rossum0df002c2000-08-27 19:21:52 +00001181int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001182PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 PyObject *m, *d, *v;
1186 const char *ext;
1187 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 m = PyImport_AddModule("__main__");
1190 if (m == NULL)
1191 return -1;
1192 d = PyModule_GetDict(m);
1193 if (PyDict_GetItemString(d, "__file__") == NULL) {
1194 PyObject *f;
Victor Stinner0fe25a42010-06-17 23:08:50 +00001195 f = PyUnicode_FromString(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (f == NULL)
1197 return -1;
1198 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1199 Py_DECREF(f);
1200 return -1;
1201 }
1202 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1203 return -1;
1204 set_file_name = 1;
1205 Py_DECREF(f);
1206 }
1207 len = strlen(filename);
1208 ext = filename + len - (len > 4 ? 4 : 0);
1209 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1210 /* Try to run a pyc file. First, re-open in binary */
1211 if (closeit)
1212 fclose(fp);
1213 if ((fp = fopen(filename, "rb")) == NULL) {
1214 fprintf(stderr, "python: Can't reopen .pyc file\n");
1215 ret = -1;
1216 goto done;
1217 }
1218 /* Turn on optimization if a .pyo file is given */
1219 if (strcmp(ext, ".pyo") == 0)
1220 Py_OptimizeFlag = 1;
1221 v = run_pyc_file(fp, filename, d, d, flags);
1222 } else {
1223 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1224 closeit, flags);
1225 }
1226 flush_io();
1227 if (v == NULL) {
1228 PyErr_Print();
1229 ret = -1;
1230 goto done;
1231 }
1232 Py_DECREF(v);
1233 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001234 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1236 PyErr_Clear();
1237 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001238}
1239
1240int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001241PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 PyObject *m, *d, *v;
1244 m = PyImport_AddModule("__main__");
1245 if (m == NULL)
1246 return -1;
1247 d = PyModule_GetDict(m);
1248 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1249 if (v == NULL) {
1250 PyErr_Print();
1251 return -1;
1252 }
1253 Py_DECREF(v);
1254 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001255}
1256
Barry Warsaw035574d1997-08-29 22:07:17 +00001257static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001258parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 long hold;
1262 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 /* old style errors */
1265 if (PyTuple_Check(err))
1266 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1267 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 if (! (v = PyObject_GetAttrString(err, "msg")))
1272 goto finally;
1273 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 if (!(v = PyObject_GetAttrString(err, "filename")))
1276 goto finally;
1277 if (v == Py_None)
1278 *filename = NULL;
1279 else if (! (*filename = _PyUnicode_AsString(v)))
1280 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 Py_DECREF(v);
1283 if (!(v = PyObject_GetAttrString(err, "lineno")))
1284 goto finally;
1285 hold = PyLong_AsLong(v);
1286 Py_DECREF(v);
1287 v = NULL;
1288 if (hold < 0 && PyErr_Occurred())
1289 goto finally;
1290 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (!(v = PyObject_GetAttrString(err, "offset")))
1293 goto finally;
1294 if (v == Py_None) {
1295 *offset = -1;
1296 Py_DECREF(v);
1297 v = NULL;
1298 } else {
1299 hold = PyLong_AsLong(v);
1300 Py_DECREF(v);
1301 v = NULL;
1302 if (hold < 0 && PyErr_Occurred())
1303 goto finally;
1304 *offset = (int)hold;
1305 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 if (!(v = PyObject_GetAttrString(err, "text")))
1308 goto finally;
1309 if (v == Py_None)
1310 *text = NULL;
1311 else if (!PyUnicode_Check(v) ||
1312 !(*text = _PyUnicode_AsString(v)))
1313 goto finally;
1314 Py_DECREF(v);
1315 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001316
1317finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 Py_XDECREF(v);
1319 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001320}
1321
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001322void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001323PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001326}
1327
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001328static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001329print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 char *nl;
1332 if (offset >= 0) {
1333 if (offset > 0 && offset == (int)strlen(text))
1334 offset--;
1335 for (;;) {
1336 nl = strchr(text, '\n');
1337 if (nl == NULL || nl-text >= offset)
1338 break;
1339 offset -= (int)(nl+1-text);
1340 text = nl+1;
1341 }
1342 while (*text == ' ' || *text == '\t') {
1343 text++;
1344 offset--;
1345 }
1346 }
1347 PyFile_WriteString(" ", f);
1348 PyFile_WriteString(text, f);
1349 if (*text == '\0' || text[strlen(text)-1] != '\n')
1350 PyFile_WriteString("\n", f);
1351 if (offset == -1)
1352 return;
1353 PyFile_WriteString(" ", f);
1354 offset--;
1355 while (offset > 0) {
1356 PyFile_WriteString(" ", f);
1357 offset--;
1358 }
1359 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001360}
1361
Guido van Rossum66e8e862001-03-23 17:54:43 +00001362static void
1363handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 PyObject *exception, *value, *tb;
1366 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (Py_InspectFlag)
1369 /* Don't exit if -i flag was given. This flag is set to 0
1370 * when entering interactive mode for inspecting. */
1371 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PyErr_Fetch(&exception, &value, &tb);
1374 fflush(stdout);
1375 if (value == NULL || value == Py_None)
1376 goto done;
1377 if (PyExceptionInstance_Check(value)) {
1378 /* The error code should be in the `code' attribute. */
1379 PyObject *code = PyObject_GetAttrString(value, "code");
1380 if (code) {
1381 Py_DECREF(value);
1382 value = code;
1383 if (value == Py_None)
1384 goto done;
1385 }
1386 /* If we failed to dig out the 'code' attribute,
1387 just let the else clause below print the error. */
1388 }
1389 if (PyLong_Check(value))
1390 exitcode = (int)PyLong_AsLong(value);
1391 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001392 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001393 if (sys_stderr != NULL && sys_stderr != Py_None) {
1394 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1395 } else {
1396 PyObject_Print(value, stderr, Py_PRINT_RAW);
1397 fflush(stderr);
1398 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 PySys_WriteStderr("\n");
1400 exitcode = 1;
1401 }
Tim Peterscf615b52003-04-19 18:47:02 +00001402 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 /* Restore and clear the exception info, in order to properly decref
1404 * the exception, value, and traceback. If we just exit instead,
1405 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1406 * some finalizers from running.
1407 */
1408 PyErr_Restore(exception, value, tb);
1409 PyErr_Clear();
1410 Py_Exit(exitcode);
1411 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001412}
1413
1414void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001415PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1420 handle_system_exit();
1421 }
1422 PyErr_Fetch(&exception, &v, &tb);
1423 if (exception == NULL)
1424 return;
1425 PyErr_NormalizeException(&exception, &v, &tb);
1426 if (tb == NULL) {
1427 tb = Py_None;
1428 Py_INCREF(tb);
1429 }
1430 PyException_SetTraceback(v, tb);
1431 if (exception == NULL)
1432 return;
1433 /* Now we know v != NULL too */
1434 if (set_sys_last_vars) {
1435 PySys_SetObject("last_type", exception);
1436 PySys_SetObject("last_value", v);
1437 PySys_SetObject("last_traceback", tb);
1438 }
1439 hook = PySys_GetObject("excepthook");
1440 if (hook) {
1441 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1442 PyObject *result = PyEval_CallObject(hook, args);
1443 if (result == NULL) {
1444 PyObject *exception2, *v2, *tb2;
1445 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1446 handle_system_exit();
1447 }
1448 PyErr_Fetch(&exception2, &v2, &tb2);
1449 PyErr_NormalizeException(&exception2, &v2, &tb2);
1450 /* It should not be possible for exception2 or v2
1451 to be NULL. However PyErr_Display() can't
1452 tolerate NULLs, so just be safe. */
1453 if (exception2 == NULL) {
1454 exception2 = Py_None;
1455 Py_INCREF(exception2);
1456 }
1457 if (v2 == NULL) {
1458 v2 = Py_None;
1459 Py_INCREF(v2);
1460 }
1461 fflush(stdout);
1462 PySys_WriteStderr("Error in sys.excepthook:\n");
1463 PyErr_Display(exception2, v2, tb2);
1464 PySys_WriteStderr("\nOriginal exception was:\n");
1465 PyErr_Display(exception, v, tb);
1466 Py_DECREF(exception2);
1467 Py_DECREF(v2);
1468 Py_XDECREF(tb2);
1469 }
1470 Py_XDECREF(result);
1471 Py_XDECREF(args);
1472 } else {
1473 PySys_WriteStderr("sys.excepthook is missing\n");
1474 PyErr_Display(exception, v, tb);
1475 }
1476 Py_XDECREF(exception);
1477 Py_XDECREF(v);
1478 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001479}
1480
Benjamin Petersone6528212008-07-15 15:32:09 +00001481static void
1482print_exception(PyObject *f, PyObject *value)
1483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 int err = 0;
1485 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 if (!PyExceptionInstance_Check(value)) {
1488 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1489 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1490 PyFile_WriteString(" found\n", f);
1491 return;
1492 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 Py_INCREF(value);
1495 fflush(stdout);
1496 type = (PyObject *) Py_TYPE(value);
1497 tb = PyException_GetTraceback(value);
1498 if (tb && tb != Py_None)
1499 err = PyTraceBack_Print(tb, f);
1500 if (err == 0 &&
1501 PyObject_HasAttrString(value, "print_file_and_line"))
1502 {
1503 PyObject *message;
1504 const char *filename, *text;
1505 int lineno, offset;
1506 if (!parse_syntax_error(value, &message, &filename,
1507 &lineno, &offset, &text))
1508 PyErr_Clear();
1509 else {
1510 char buf[10];
1511 PyFile_WriteString(" File \"", f);
1512 if (filename == NULL)
1513 PyFile_WriteString("<string>", f);
1514 else
1515 PyFile_WriteString(filename, f);
1516 PyFile_WriteString("\", line ", f);
1517 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1518 PyFile_WriteString(buf, f);
1519 PyFile_WriteString("\n", f);
1520 if (text != NULL)
1521 print_error_text(f, offset, text);
1522 Py_DECREF(value);
1523 value = message;
1524 /* Can't be bothered to check all those
1525 PyFile_WriteString() calls */
1526 if (PyErr_Occurred())
1527 err = -1;
1528 }
1529 }
1530 if (err) {
1531 /* Don't do anything else */
1532 }
1533 else {
1534 PyObject* moduleName;
1535 char* className;
1536 assert(PyExceptionClass_Check(type));
1537 className = PyExceptionClass_Name(type);
1538 if (className != NULL) {
1539 char *dot = strrchr(className, '.');
1540 if (dot != NULL)
1541 className = dot+1;
1542 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 moduleName = PyObject_GetAttrString(type, "__module__");
1545 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1546 {
1547 Py_DECREF(moduleName);
1548 err = PyFile_WriteString("<unknown>", f);
1549 }
1550 else {
1551 char* modstr = _PyUnicode_AsString(moduleName);
1552 if (modstr && strcmp(modstr, "builtins"))
1553 {
1554 err = PyFile_WriteString(modstr, f);
1555 err += PyFile_WriteString(".", f);
1556 }
1557 Py_DECREF(moduleName);
1558 }
1559 if (err == 0) {
1560 if (className == NULL)
1561 err = PyFile_WriteString("<unknown>", f);
1562 else
1563 err = PyFile_WriteString(className, f);
1564 }
1565 }
1566 if (err == 0 && (value != Py_None)) {
1567 PyObject *s = PyObject_Str(value);
1568 /* only print colon if the str() of the
1569 object is not the empty string
1570 */
1571 if (s == NULL)
1572 err = -1;
1573 else if (!PyUnicode_Check(s) ||
1574 PyUnicode_GetSize(s) != 0)
1575 err = PyFile_WriteString(": ", f);
1576 if (err == 0)
1577 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1578 Py_XDECREF(s);
1579 }
1580 /* try to write a newline in any case */
1581 err += PyFile_WriteString("\n", f);
1582 Py_XDECREF(tb);
1583 Py_DECREF(value);
1584 /* If an error happened here, don't show it.
1585 XXX This is wrong, but too many callers rely on this behavior. */
1586 if (err != 0)
1587 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001588}
1589
1590static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 "\nThe above exception was the direct cause "
1592 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001593
1594static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 "\nDuring handling of the above exception, "
1596 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001597
1598static void
1599print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 int err = 0, res;
1602 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 if (seen != NULL) {
1605 /* Exception chaining */
1606 if (PySet_Add(seen, value) == -1)
1607 PyErr_Clear();
1608 else if (PyExceptionInstance_Check(value)) {
1609 cause = PyException_GetCause(value);
1610 context = PyException_GetContext(value);
1611 if (cause) {
1612 res = PySet_Contains(seen, cause);
1613 if (res == -1)
1614 PyErr_Clear();
1615 if (res == 0) {
1616 print_exception_recursive(
1617 f, cause, seen);
1618 err |= PyFile_WriteString(
1619 cause_message, f);
1620 }
1621 }
1622 else if (context) {
1623 res = PySet_Contains(seen, context);
1624 if (res == -1)
1625 PyErr_Clear();
1626 if (res == 0) {
1627 print_exception_recursive(
1628 f, context, seen);
1629 err |= PyFile_WriteString(
1630 context_message, f);
1631 }
1632 }
1633 Py_XDECREF(context);
1634 Py_XDECREF(cause);
1635 }
1636 }
1637 print_exception(f, value);
1638 if (err != 0)
1639 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001640}
1641
Thomas Wouters477c8d52006-05-27 19:21:47 +00001642void
1643PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 PyObject *seen;
1646 PyObject *f = PySys_GetObject("stderr");
1647 if (f == Py_None) {
1648 /* pass */
1649 }
1650 else if (f == NULL) {
1651 _PyObject_Dump(value);
1652 fprintf(stderr, "lost sys.stderr\n");
1653 }
1654 else {
1655 /* We choose to ignore seen being possibly NULL, and report
1656 at least the main exception (it could be a MemoryError).
1657 */
1658 seen = PySet_New(NULL);
1659 if (seen == NULL)
1660 PyErr_Clear();
1661 print_exception_recursive(f, value, seen);
1662 Py_XDECREF(seen);
1663 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001664}
1665
Guido van Rossum82598051997-03-05 00:20:32 +00001666PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001667PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 PyObject *ret = NULL;
1671 mod_ty mod;
1672 PyArena *arena = PyArena_New();
1673 if (arena == NULL)
1674 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1677 if (mod != NULL)
1678 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1679 PyArena_Free(arena);
1680 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001681}
1682
1683PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001684PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyObject *ret;
1688 mod_ty mod;
1689 PyArena *arena = PyArena_New();
1690 if (arena == NULL)
1691 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1694 flags, NULL, arena);
1695 if (closeit)
1696 fclose(fp);
1697 if (mod == NULL) {
1698 PyArena_Free(arena);
1699 return NULL;
1700 }
1701 ret = run_mod(mod, filename, globals, locals, flags, arena);
1702 PyArena_Free(arena);
1703 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001704}
1705
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001706static void
1707flush_io(void)
1708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 PyObject *f, *r;
1710 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 /* Save the current exception */
1713 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 f = PySys_GetObject("stderr");
1716 if (f != NULL) {
1717 r = PyObject_CallMethod(f, "flush", "");
1718 if (r)
1719 Py_DECREF(r);
1720 else
1721 PyErr_Clear();
1722 }
1723 f = PySys_GetObject("stdout");
1724 if (f != NULL) {
1725 r = PyObject_CallMethod(f, "flush", "");
1726 if (r)
1727 Py_DECREF(r);
1728 else
1729 PyErr_Clear();
1730 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001733}
1734
Guido van Rossum82598051997-03-05 00:20:32 +00001735static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001736run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 PyCodeObject *co;
1740 PyObject *v;
1741 co = PyAST_Compile(mod, filename, flags, arena);
1742 if (co == NULL)
1743 return NULL;
1744 v = PyEval_EvalCode(co, globals, locals);
1745 Py_DECREF(co);
1746 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001747}
1748
Guido van Rossum82598051997-03-05 00:20:32 +00001749static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001750run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 PyCodeObject *co;
1754 PyObject *v;
1755 long magic;
1756 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 magic = PyMarshal_ReadLongFromFile(fp);
1759 if (magic != PyImport_GetMagicNumber()) {
1760 PyErr_SetString(PyExc_RuntimeError,
1761 "Bad magic number in .pyc file");
1762 return NULL;
1763 }
1764 (void) PyMarshal_ReadLongFromFile(fp);
1765 v = PyMarshal_ReadLastObjectFromFile(fp);
1766 fclose(fp);
1767 if (v == NULL || !PyCode_Check(v)) {
1768 Py_XDECREF(v);
1769 PyErr_SetString(PyExc_RuntimeError,
1770 "Bad code object in .pyc file");
1771 return NULL;
1772 }
1773 co = (PyCodeObject *)v;
1774 v = PyEval_EvalCode(co, globals, locals);
1775 if (v && flags)
1776 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1777 Py_DECREF(co);
1778 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001779}
1780
Guido van Rossum82598051997-03-05 00:20:32 +00001781PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001782Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 PyCodeObject *co;
1786 mod_ty mod;
1787 PyArena *arena = PyArena_New();
1788 if (arena == NULL)
1789 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1792 if (mod == NULL) {
1793 PyArena_Free(arena);
1794 return NULL;
1795 }
1796 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1797 PyObject *result = PyAST_mod2obj(mod);
1798 PyArena_Free(arena);
1799 return result;
1800 }
1801 co = PyAST_Compile(mod, filename, flags, arena);
1802 PyArena_Free(arena);
1803 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001804}
1805
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001806struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001807Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 struct symtable *st;
1810 mod_ty mod;
1811 PyCompilerFlags flags;
1812 PyArena *arena = PyArena_New();
1813 if (arena == NULL)
1814 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 flags.cf_flags = 0;
1817 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1818 if (mod == NULL) {
1819 PyArena_Free(arena);
1820 return NULL;
1821 }
1822 st = PySymtable_Build(mod, filename, 0);
1823 PyArena_Free(arena);
1824 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001825}
1826
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827/* Preferred access to parser is through AST. */
1828mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001829PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 mod_ty mod;
1833 PyCompilerFlags localflags;
1834 perrdetail err;
1835 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1838 &_PyParser_Grammar, start, &err,
1839 &iflags);
1840 if (flags == NULL) {
1841 localflags.cf_flags = 0;
1842 flags = &localflags;
1843 }
1844 if (n) {
1845 flags->cf_flags |= iflags & PyCF_MASK;
1846 mod = PyAST_FromNode(n, flags, filename, arena);
1847 PyNode_Free(n);
1848 return mod;
1849 }
1850 else {
1851 err_input(&err);
1852 return NULL;
1853 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001854}
1855
1856mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001857PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 int start, char *ps1,
1859 char *ps2, PyCompilerFlags *flags, int *errcode,
1860 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 mod_ty mod;
1863 PyCompilerFlags localflags;
1864 perrdetail err;
1865 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1868 &_PyParser_Grammar,
1869 start, ps1, ps2, &err, &iflags);
1870 if (flags == NULL) {
1871 localflags.cf_flags = 0;
1872 flags = &localflags;
1873 }
1874 if (n) {
1875 flags->cf_flags |= iflags & PyCF_MASK;
1876 mod = PyAST_FromNode(n, flags, filename, arena);
1877 PyNode_Free(n);
1878 return mod;
1879 }
1880 else {
1881 err_input(&err);
1882 if (errcode)
1883 *errcode = err.error;
1884 return NULL;
1885 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001886}
1887
Guido van Rossuma110aa61994-08-29 12:50:44 +00001888/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001889
Guido van Rossuma110aa61994-08-29 12:50:44 +00001890node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001891PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001893 perrdetail err;
1894 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1895 &_PyParser_Grammar,
1896 start, NULL, NULL, &err, flags);
1897 if (n == NULL)
1898 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001901}
1902
Guido van Rossuma110aa61994-08-29 12:50:44 +00001903/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001904
Guido van Rossuma110aa61994-08-29 12:50:44 +00001905node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001906PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 perrdetail err;
1909 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1910 start, &err, flags);
1911 if (n == NULL)
1912 err_input(&err);
1913 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001914}
1915
1916node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001917PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 perrdetail err;
1921 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1922 &_PyParser_Grammar, start, &err, flags);
1923 if (n == NULL)
1924 err_input(&err);
1925 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001926}
1927
1928node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001929PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001932}
1933
Guido van Rossum66ebd912003-04-17 16:02:26 +00001934/* May want to move a more generalized form of this to parsetok.c or
1935 even parser modules. */
1936
1937void
1938PyParser_SetError(perrdetail *err)
1939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001941}
1942
Guido van Rossuma110aa61994-08-29 12:50:44 +00001943/* Set the error appropriate to the given input error code (see errcode.h) */
1944
1945static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001946err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 PyObject *v, *w, *errtype, *errtext;
1949 PyObject *msg_obj = NULL;
1950 char *msg = NULL;
1951 errtype = PyExc_SyntaxError;
1952 switch (err->error) {
1953 case E_ERROR:
1954 return;
1955 case E_SYNTAX:
1956 errtype = PyExc_IndentationError;
1957 if (err->expected == INDENT)
1958 msg = "expected an indented block";
1959 else if (err->token == INDENT)
1960 msg = "unexpected indent";
1961 else if (err->token == DEDENT)
1962 msg = "unexpected unindent";
1963 else {
1964 errtype = PyExc_SyntaxError;
1965 msg = "invalid syntax";
1966 }
1967 break;
1968 case E_TOKEN:
1969 msg = "invalid token";
1970 break;
1971 case E_EOFS:
1972 msg = "EOF while scanning triple-quoted string literal";
1973 break;
1974 case E_EOLS:
1975 msg = "EOL while scanning string literal";
1976 break;
1977 case E_INTR:
1978 if (!PyErr_Occurred())
1979 PyErr_SetNone(PyExc_KeyboardInterrupt);
1980 goto cleanup;
1981 case E_NOMEM:
1982 PyErr_NoMemory();
1983 goto cleanup;
1984 case E_EOF:
1985 msg = "unexpected EOF while parsing";
1986 break;
1987 case E_TABSPACE:
1988 errtype = PyExc_TabError;
1989 msg = "inconsistent use of tabs and spaces in indentation";
1990 break;
1991 case E_OVERFLOW:
1992 msg = "expression too long";
1993 break;
1994 case E_DEDENT:
1995 errtype = PyExc_IndentationError;
1996 msg = "unindent does not match any outer indentation level";
1997 break;
1998 case E_TOODEEP:
1999 errtype = PyExc_IndentationError;
2000 msg = "too many levels of indentation";
2001 break;
2002 case E_DECODE: {
2003 PyObject *type, *value, *tb;
2004 PyErr_Fetch(&type, &value, &tb);
2005 msg = "unknown decode error";
2006 if (value != NULL)
2007 msg_obj = PyObject_Str(value);
2008 Py_XDECREF(type);
2009 Py_XDECREF(value);
2010 Py_XDECREF(tb);
2011 break;
2012 }
2013 case E_LINECONT:
2014 msg = "unexpected character after line continuation character";
2015 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 case E_IDENTIFIER:
2018 msg = "invalid character in identifier";
2019 break;
2020 default:
2021 fprintf(stderr, "error=%d\n", err->error);
2022 msg = "unknown parsing error";
2023 break;
2024 }
2025 /* err->text may not be UTF-8 in case of decoding errors.
2026 Explicitly convert to an object. */
2027 if (!err->text) {
2028 errtext = Py_None;
2029 Py_INCREF(Py_None);
2030 } else {
2031 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2032 "replace");
2033 }
2034 v = Py_BuildValue("(ziiN)", err->filename,
2035 err->lineno, err->offset, errtext);
2036 if (v != NULL) {
2037 if (msg_obj)
2038 w = Py_BuildValue("(OO)", msg_obj, v);
2039 else
2040 w = Py_BuildValue("(sO)", msg, v);
2041 } else
2042 w = NULL;
2043 Py_XDECREF(v);
2044 PyErr_SetObject(errtype, w);
2045 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002046cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 Py_XDECREF(msg_obj);
2048 if (err->text != NULL) {
2049 PyObject_FREE(err->text);
2050 err->text = NULL;
2051 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002052}
2053
2054/* Print fatal error message and abort */
2055
2056void
Tim Peters7c321a82002-07-09 02:57:01 +00002057Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 fprintf(stderr, "Fatal Python error: %s\n", msg);
2060 fflush(stderr); /* it helps in Windows debug build */
2061 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002062 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002064#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 {
2066 size_t len = strlen(msg);
2067 WCHAR* buffer;
2068 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 /* Convert the message to wchar_t. This uses a simple one-to-one
2071 conversion, assuming that the this error message actually uses ASCII
2072 only. If this ceases to be true, we will have to convert. */
2073 buffer = alloca( (len+1) * (sizeof *buffer));
2074 for( i=0; i<=len; ++i)
2075 buffer[i] = msg[i];
2076 OutputDebugStringW(L"Fatal Python error: ");
2077 OutputDebugStringW(buffer);
2078 OutputDebugStringW(L"\n");
2079 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002080#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002082#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002083#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002085}
2086
2087/* Clean up and exit */
2088
Guido van Rossuma110aa61994-08-29 12:50:44 +00002089#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002090#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002091#endif
2092
Collin Winter670e6922007-03-21 02:57:17 +00002093static void (*pyexitfunc)(void) = NULL;
2094/* For the atexit module. */
2095void _Py_PyAtExit(void (*func)(void))
2096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002098}
2099
2100static void
2101call_py_exitfuncs(void)
2102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 if (pyexitfunc == NULL)
2104 return;
Collin Winter670e6922007-03-21 02:57:17 +00002105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 (*pyexitfunc)();
2107 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002108}
2109
Antoine Pitrou011bd622009-10-20 21:52:47 +00002110/* Wait until threading._shutdown completes, provided
2111 the threading module was imported in the first place.
2112 The shutdown routine will wait until all non-daemon
2113 "threading" threads have completed. */
2114static void
2115wait_for_thread_shutdown(void)
2116{
2117#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 PyObject *result;
2119 PyThreadState *tstate = PyThreadState_GET();
2120 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2121 "threading");
2122 if (threading == NULL) {
2123 /* threading not imported */
2124 PyErr_Clear();
2125 return;
2126 }
2127 result = PyObject_CallMethod(threading, "_shutdown", "");
2128 if (result == NULL) {
2129 PyErr_WriteUnraisable(threading);
2130 }
2131 else {
2132 Py_DECREF(result);
2133 }
2134 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002135#endif
2136}
2137
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002138#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002139static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002140static int nexitfuncs = 0;
2141
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002142int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 if (nexitfuncs >= NEXITFUNCS)
2145 return -1;
2146 exitfuncs[nexitfuncs++] = func;
2147 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002148}
2149
Guido van Rossumcc283f51997-08-05 02:22:03 +00002150static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002151call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 while (nexitfuncs > 0)
2154 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 fflush(stdout);
2157 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002158}
2159
2160void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002161Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002166}
2167
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002168static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002169initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002170{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002171#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002173#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002174#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002176#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002177#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002179#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002181}
2182
Guido van Rossum7433b121997-02-14 19:45:36 +00002183
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002184/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2185 *
2186 * All of the code in this function must only use async-signal-safe functions,
2187 * listed at `man 7 signal` or
2188 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2189 */
2190void
2191_Py_RestoreSignals(void)
2192{
2193#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002195#endif
2196#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002198#endif
2199#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002201#endif
2202}
2203
2204
Guido van Rossum7433b121997-02-14 19:45:36 +00002205/*
2206 * The file descriptor fd is considered ``interactive'' if either
2207 * a) isatty(fd) is TRUE, or
2208 * b) the -i flag was given, and the filename associated with
2209 * the descriptor is NULL or "<stdin>" or "???".
2210 */
2211int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002212Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (isatty((int)fileno(fp)))
2215 return 1;
2216 if (!Py_InteractiveFlag)
2217 return 0;
2218 return (filename == NULL) ||
2219 (strcmp(filename, "<stdin>") == 0) ||
2220 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002221}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002222
2223
Tim Petersd08e3822003-04-17 15:24:21 +00002224#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002225#if defined(WIN32) && defined(_MSC_VER)
2226
2227/* Stack checking for Microsoft C */
2228
2229#include <malloc.h>
2230#include <excpt.h>
2231
Fred Drakee8de31c2000-08-31 05:38:39 +00002232/*
2233 * Return non-zero when we run out of memory on the stack; zero otherwise.
2234 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002235int
Fred Drake399739f2000-08-31 05:52:44 +00002236PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 __try {
2239 /* alloca throws a stack overflow exception if there's
2240 not enough space left on the stack */
2241 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2242 return 0;
2243 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2244 EXCEPTION_EXECUTE_HANDLER :
2245 EXCEPTION_CONTINUE_SEARCH) {
2246 int errcode = _resetstkoflw();
2247 if (errcode == 0)
2248 {
2249 Py_FatalError("Could not reset the stack!");
2250 }
2251 }
2252 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002253}
2254
2255#endif /* WIN32 && _MSC_VER */
2256
2257/* Alternate implementations can be added here... */
2258
2259#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002260
2261
2262/* Wrappers around sigaction() or signal(). */
2263
2264PyOS_sighandler_t
2265PyOS_getsig(int sig)
2266{
2267#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 struct sigaction context;
2269 if (sigaction(sig, NULL, &context) == -1)
2270 return SIG_ERR;
2271 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002272#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002274/* Special signal handling for the secure CRT in Visual Studio 2005 */
2275#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 switch (sig) {
2277 /* Only these signals are valid */
2278 case SIGINT:
2279 case SIGILL:
2280 case SIGFPE:
2281 case SIGSEGV:
2282 case SIGTERM:
2283 case SIGBREAK:
2284 case SIGABRT:
2285 break;
2286 /* Don't call signal() with other values or it will assert */
2287 default:
2288 return SIG_ERR;
2289 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002290#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 handler = signal(sig, SIG_IGN);
2292 if (handler != SIG_ERR)
2293 signal(sig, handler);
2294 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002295#endif
2296}
2297
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002298/*
2299 * All of the code in this function must only use async-signal-safe functions,
2300 * listed at `man 7 signal` or
2301 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2302 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002303PyOS_sighandler_t
2304PyOS_setsig(int sig, PyOS_sighandler_t handler)
2305{
2306#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 /* Some code in Modules/signalmodule.c depends on sigaction() being
2308 * used here if HAVE_SIGACTION is defined. Fix that if this code
2309 * changes to invalidate that assumption.
2310 */
2311 struct sigaction context, ocontext;
2312 context.sa_handler = handler;
2313 sigemptyset(&context.sa_mask);
2314 context.sa_flags = 0;
2315 if (sigaction(sig, &context, &ocontext) == -1)
2316 return SIG_ERR;
2317 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002318#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 PyOS_sighandler_t oldhandler;
2320 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002321#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002323#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002325#endif
2326}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327
2328/* Deprecated C API functions still provided for binary compatiblity */
2329
2330#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002331PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002332PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335}
2336
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002337#undef PyParser_SimpleParseString
2338PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002339PyParser_SimpleParseString(const char *str, int start)
2340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002342}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002343
2344#undef PyRun_AnyFile
2345PyAPI_FUNC(int)
2346PyRun_AnyFile(FILE *fp, const char *name)
2347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002349}
2350
2351#undef PyRun_AnyFileEx
2352PyAPI_FUNC(int)
2353PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002356}
2357
2358#undef PyRun_AnyFileFlags
2359PyAPI_FUNC(int)
2360PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002363}
2364
2365#undef PyRun_File
2366PyAPI_FUNC(PyObject *)
2367PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002370}
2371
2372#undef PyRun_FileEx
2373PyAPI_FUNC(PyObject *)
2374PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002377}
2378
2379#undef PyRun_FileFlags
2380PyAPI_FUNC(PyObject *)
2381PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002385}
2386
2387#undef PyRun_SimpleFile
2388PyAPI_FUNC(int)
2389PyRun_SimpleFile(FILE *f, const char *p)
2390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002392}
2393
2394#undef PyRun_SimpleFileEx
2395PyAPI_FUNC(int)
2396PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002399}
2400
2401
2402#undef PyRun_String
2403PyAPI_FUNC(PyObject *)
2404PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002407}
2408
2409#undef PyRun_SimpleString
2410PyAPI_FUNC(int)
2411PyRun_SimpleString(const char *s)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002414}
2415
2416#undef Py_CompileString
2417PyAPI_FUNC(PyObject *)
2418Py_CompileString(const char *str, const char *p, int s)
2419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002421}
2422
2423#undef PyRun_InteractiveOne
2424PyAPI_FUNC(int)
2425PyRun_InteractiveOne(FILE *f, const char *p)
2426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002428}
2429
2430#undef PyRun_InteractiveLoop
2431PyAPI_FUNC(int)
2432PyRun_InteractiveLoop(FILE *f, const char *p)
2433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002435}
2436
2437#ifdef __cplusplus
2438}
2439#endif