blob: fd31974cb85dc7a03eed09ab9a5c711f48d5a696 [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 +0000137static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000138get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000139{
Victor Stinner94908bb2010-08-18 21:23:25 +0000140 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000141 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000142
Victor Stinner94908bb2010-08-18 21:23:25 +0000143 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 if (!codec)
145 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 name = PyObject_GetAttrString(codec, "name");
148 Py_CLEAR(codec);
149 if (!name)
150 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000151
Victor Stinner94908bb2010-08-18 21:23:25 +0000152 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner386fe712010-05-19 00:34:15 +0000153 if (name == NULL)
154 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000155 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000157 if (name_str == NULL) {
158 PyErr_NoMemory();
159 return NULL;
160 }
161 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000162
163error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000165 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000167}
Victor Stinner94908bb2010-08-18 21:23:25 +0000168
169#if defined(HAVE_LANGINFO_H) && defined(CODESET)
170static char*
171get_codeset(void)
172{
173 char* codeset = nl_langinfo(CODESET);
174 if (!codeset || codeset[0] == '\0') {
175 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
176 return NULL;
177 }
178 return get_codec_name(codeset);
179}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000180#endif
181
Guido van Rossuma027efa1997-05-05 20:56:21 +0000182void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000183Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyInterpreterState *interp;
186 PyThreadState *tstate;
187 PyObject *bimod, *sysmod, *pstderr;
188 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (initialized)
192 return;
193 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000194
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000195#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 /* Set up the LC_CTYPE locale, so we can obtain
197 the locale's charset without having to switch
198 locales. */
199 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000200#endif
201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
203 Py_DebugFlag = add_flag(Py_DebugFlag, p);
204 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
205 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
206 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
207 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
208 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
209 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 interp = PyInterpreterState_New();
212 if (interp == NULL)
213 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 tstate = PyThreadState_New(interp);
216 if (tstate == NULL)
217 Py_FatalError("Py_Initialize: can't make first thread");
218 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000219
Victor Stinner6961bd62010-08-17 22:26:51 +0000220 /* auto-thread-state API, if available */
221#ifdef WITH_THREAD
222 _PyGILState_Init(interp, tstate);
223#endif /* WITH_THREAD */
224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 if (!_PyFrame_Init())
228 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (!_PyLong_Init())
231 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (!PyByteArray_Init())
234 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 interp->modules = PyDict_New();
239 if (interp->modules == NULL)
240 Py_FatalError("Py_Initialize: can't make modules dictionary");
241 interp->modules_reloading = PyDict_New();
242 if (interp->modules_reloading == NULL)
243 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 /* Init Unicode implementation; relies on the codec registry */
246 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 bimod = _PyBuiltin_Init();
249 if (bimod == NULL)
250 Py_FatalError("Py_Initialize: can't initialize builtins modules");
251 _PyImport_FixupExtension(bimod, "builtins", "builtins");
252 interp->builtins = PyModule_GetDict(bimod);
253 if (interp->builtins == NULL)
254 Py_FatalError("Py_Initialize: can't initialize builtins dict");
255 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 /* initialize builtin exceptions */
258 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 sysmod = _PySys_Init();
261 if (sysmod == NULL)
262 Py_FatalError("Py_Initialize: can't initialize sys");
263 interp->sysdict = PyModule_GetDict(sysmod);
264 if (interp->sysdict == NULL)
265 Py_FatalError("Py_Initialize: can't initialize sys dict");
266 Py_INCREF(interp->sysdict);
267 _PyImport_FixupExtension(sysmod, "sys", "sys");
268 PySys_SetPath(Py_GetPath());
269 PyDict_SetItemString(interp->sysdict, "modules",
270 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 /* Set up a preliminary stderr printer until we have enough
273 infrastructure for the io module in place. */
274 pstderr = PyFile_NewStdPrinter(fileno(stderr));
275 if (pstderr == NULL)
276 Py_FatalError("Py_Initialize: can't set preliminary stderr");
277 PySys_SetObject("stderr", pstderr);
278 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000283
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000284 /* Initialize _warnings. */
285 _PyWarnings_Init();
286
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000287 _PyTime_Init();
288
Victor Stinnerb744ba12010-05-15 12:27:16 +0000289 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 if (install_sigs)
292 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 /* Initialize warnings. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 if (PySys_HasWarnOptions()) {
296 PyObject *warnings_module = PyImport_ImportModule("warnings");
297 if (!warnings_module)
298 PyErr_Clear();
299 Py_XDECREF(warnings_module);
300 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 initmain(); /* Module __main__ */
303 if (initstdio() < 0)
304 Py_FatalError(
305 "Py_Initialize: can't initialize sys standard streams");
306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (!Py_NoSiteFlag)
308 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000309}
310
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000311void
312Py_Initialize(void)
313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000315}
316
317
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000318#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000319extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000320#endif
321
Guido van Rossume8432ac2007-07-09 15:04:50 +0000322/* Flush stdout and stderr */
323
Neal Norwitz2bad9702007-08-27 06:19:22 +0000324static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000325flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 PyObject *fout = PySys_GetObject("stdout");
328 PyObject *ferr = PySys_GetObject("stderr");
329 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 if (fout != NULL && fout != Py_None) {
332 tmp = PyObject_CallMethod(fout, "flush", "");
333 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000334 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 else
336 Py_DECREF(tmp);
337 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000338
Victor Stinner9467b212010-05-14 00:59:09 +0000339 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 tmp = PyObject_CallMethod(ferr, "flush", "");
341 if (tmp == NULL)
342 PyErr_Clear();
343 else
344 Py_DECREF(tmp);
345 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000346}
347
Guido van Rossum25ce5661997-08-02 03:10:38 +0000348/* Undo the effect of Py_Initialize().
349
350 Beware: if multiple interpreter and/or thread states exist, these
351 are not wiped out; only the current thread and interpreter state
352 are deleted. But since everything else is deleted, those other
353 interpreter and thread states should no longer be used.
354
355 (XXX We should do better, e.g. wipe out all interpreters and
356 threads.)
357
358 Locking: as above.
359
360*/
361
362void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000363Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 PyInterpreterState *interp;
366 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (!initialized)
369 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 /* The interpreter is still entirely intact at this point, and the
374 * exit funcs may be relying on that. In particular, if some thread
375 * or exit func is still waiting to do an import, the import machinery
376 * expects Py_IsInitialized() to return true. So don't say the
377 * interpreter is uninitialized until after the exit funcs have run.
378 * Note that Threading.py uses an exit func to do a join on all the
379 * threads created thru it, so this also protects pending imports in
380 * the threads created via Threading.
381 */
382 call_py_exitfuncs();
383 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 /* Flush stdout+stderr */
386 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 /* Get current thread state and interpreter pointer */
389 tstate = PyThreadState_GET();
390 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 /* Disable signal handling */
393 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Clear type lookup cache */
396 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 /* Collect garbage. This may call finalizers; it's nice to call these
399 * before all modules are destroyed.
400 * XXX If a __del__ or weakref callback is triggered here, and tries to
401 * XXX import a module, bad things can happen, because Python no
402 * XXX longer believes it's initialized.
403 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
404 * XXX is easy to provoke that way. I've also seen, e.g.,
405 * XXX Exception exceptions.ImportError: 'No module named sha'
406 * XXX in <function callback at 0x008F5718> ignored
407 * XXX but I'm unclear on exactly how that one happens. In any case,
408 * XXX I haven't seen a real-life report of either of these.
409 */
410 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000411#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 /* With COUNT_ALLOCS, it helps to run GC multiple times:
413 each collection might release some types from the type
414 list, so they become garbage. */
415 while (PyGC_Collect() > 0)
416 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000417#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000418 /* We run this while most interpreter state is still alive, so that
419 debug information can be printed out */
420 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 /* Destroy all modules */
423 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 /* Flush stdout+stderr (again, in case more was printed) */
426 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 /* Collect final garbage. This disposes of cycles created by
429 * new-style class definitions, for example.
430 * XXX This is disabled because it caused too many problems. If
431 * XXX a __del__ or weakref callback triggers here, Python code has
432 * XXX a hard time running, because even the sys module has been
433 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
434 * XXX One symptom is a sequence of information-free messages
435 * XXX coming from threads (if a __del__ or callback is invoked,
436 * XXX other threads can execute too, and any exception they encounter
437 * XXX triggers a comedy of errors as subsystem after subsystem
438 * XXX fails to find what it *expects* to find in sys to help report
439 * XXX the exception and consequent unexpected failures). I've also
440 * XXX seen segfaults then, after adding print statements to the
441 * XXX Python code getting called.
442 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000443#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000445#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
448 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000451#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000453#endif
454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000456
Tim Peters9cf25ce2003-04-17 15:21:01 +0000457#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 /* Display all objects still alive -- this can invoke arbitrary
459 * __repr__ overrides, so requires a mostly-intact interpreter.
460 * Alas, a lot of stuff may still be alive now that will be cleaned
461 * up later.
462 */
463 if (Py_GETENV("PYTHONDUMPREFS"))
464 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000465#endif /* Py_TRACE_REFS */
466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 /* Clear interpreter state */
468 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 /* Now we decref the exception classes. After this point nothing
471 can raise an exception. That's okay, because each Fini() method
472 below has been checked to make sure no exceptions are ever
473 raised.
474 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000479#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000481#endif /* WITH_THREAD */
482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 /* Delete current thread */
484 PyThreadState_Swap(NULL);
485 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 /* Sundry finalizers */
488 PyMethod_Fini();
489 PyFrame_Fini();
490 PyCFunction_Fini();
491 PyTuple_Fini();
492 PyList_Fini();
493 PySet_Fini();
494 PyBytes_Fini();
495 PyByteArray_Fini();
496 PyLong_Fini();
497 PyFloat_Fini();
498 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* Cleanup Unicode implementation */
501 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000504 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 free((char*)Py_FileSystemDefaultEncoding);
506 Py_FileSystemDefaultEncoding = NULL;
507 }
Christian Heimesc8967002007-11-30 10:18:26 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* XXX Still allocated:
510 - various static ad-hoc pointers to interned strings
511 - int and float free list blocks
512 - whatever various modules and libraries allocate
513 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000516
Tim Peters269b2a62003-04-17 19:52:29 +0000517#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* Display addresses (& refcnts) of all objects still alive.
519 * An address can be used to find the repr of the object, printed
520 * above by _Py_PrintReferences.
521 */
522 if (Py_GETENV("PYTHONDUMPREFS"))
523 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000524#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000525#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 if (Py_GETENV("PYTHONMALLOCSTATS"))
527 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000528#endif
529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000531}
532
533/* Create and initialize a new interpreter and thread, and return the
534 new thread. This requires that Py_Initialize() has been called
535 first.
536
537 Unsuccessful initialization yields a NULL pointer. Note that *no*
538 exception information is available even in this case -- the
539 exception information is held in the thread, and there is no
540 thread.
541
542 Locking: as above.
543
544*/
545
546PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000547Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 PyInterpreterState *interp;
550 PyThreadState *tstate, *save_tstate;
551 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 if (!initialized)
554 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 interp = PyInterpreterState_New();
557 if (interp == NULL)
558 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 tstate = PyThreadState_New(interp);
561 if (tstate == NULL) {
562 PyInterpreterState_Delete(interp);
563 return NULL;
564 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 interp->modules = PyDict_New();
571 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 bimod = _PyImport_FindExtension("builtins", "builtins");
574 if (bimod != NULL) {
575 interp->builtins = PyModule_GetDict(bimod);
576 if (interp->builtins == NULL)
577 goto handle_error;
578 Py_INCREF(interp->builtins);
579 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 /* initialize builtin exceptions */
582 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 sysmod = _PyImport_FindExtension("sys", "sys");
585 if (bimod != NULL && sysmod != NULL) {
586 PyObject *pstderr;
587 interp->sysdict = PyModule_GetDict(sysmod);
588 if (interp->sysdict == NULL)
589 goto handle_error;
590 Py_INCREF(interp->sysdict);
591 PySys_SetPath(Py_GetPath());
592 PyDict_SetItemString(interp->sysdict, "modules",
593 interp->modules);
594 /* Set up a preliminary stderr printer until we have enough
595 infrastructure for the io module in place. */
596 pstderr = PyFile_NewStdPrinter(fileno(stderr));
597 if (pstderr == NULL)
598 Py_FatalError("Py_Initialize: can't set preliminary stderr");
599 PySys_SetObject("stderr", pstderr);
600 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 _PyImportHooks_Init();
603 if (initstdio() < 0)
604 Py_FatalError(
605 "Py_Initialize: can't initialize sys standard streams");
606 initmain();
607 if (!Py_NoSiteFlag)
608 initsite();
609 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!PyErr_Occurred())
612 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000613
Thomas Wouters89f507f2006-12-13 04:49:30 +0000614handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 PyErr_Print();
618 PyThreadState_Clear(tstate);
619 PyThreadState_Swap(save_tstate);
620 PyThreadState_Delete(tstate);
621 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000624}
625
626/* Delete an interpreter and its last thread. This requires that the
627 given thread state is current, that the thread has no remaining
628 frames, and that it is its interpreter's only remaining thread.
629 It is a fatal error to violate these constraints.
630
631 (Py_Finalize() doesn't have these constraints -- it zaps
632 everything, regardless.)
633
634 Locking: as above.
635
636*/
637
638void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000639Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 if (tstate != PyThreadState_GET())
644 Py_FatalError("Py_EndInterpreter: thread is not current");
645 if (tstate->frame != NULL)
646 Py_FatalError("Py_EndInterpreter: thread still has a frame");
647 if (tstate != interp->tstate_head || tstate->next != NULL)
648 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 PyImport_Cleanup();
651 PyInterpreterState_Clear(interp);
652 PyThreadState_Swap(NULL);
653 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000654}
655
Martin v. Löwis790465f2008-04-05 20:41:37 +0000656static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000657
658void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000659Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (pn && *pn)
662 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000663}
664
Martin v. Löwis790465f2008-04-05 20:41:37 +0000665wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000666Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000669}
670
Martin v. Löwis790465f2008-04-05 20:41:37 +0000671static wchar_t *default_home = NULL;
672static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000673
674void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000675Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000678}
679
Martin v. Löwis790465f2008-04-05 20:41:37 +0000680wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000681Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 wchar_t *home = default_home;
684 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
685 char* chome = Py_GETENV("PYTHONHOME");
686 if (chome) {
687 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
688 if (r != (size_t)-1 && r <= PATH_MAX)
689 home = env_home;
690 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 }
693 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000694}
695
Guido van Rossum6135a871995-01-09 17:53:26 +0000696/* Create __main__ module */
697
698static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000699initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 PyObject *m, *d;
702 m = PyImport_AddModule("__main__");
703 if (m == NULL)
704 Py_FatalError("can't create __main__ module");
705 d = PyModule_GetDict(m);
706 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
707 PyObject *bimod = PyImport_ImportModule("builtins");
708 if (bimod == NULL ||
709 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
710 Py_FatalError("can't add __builtins__ to __main__");
711 Py_DECREF(bimod);
712 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000713}
714
Victor Stinnerb744ba12010-05-15 12:27:16 +0000715static void
716initfsencoding(void)
717{
718 PyObject *codec;
719#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000720 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000721
Victor Stinner7f84ab52010-06-11 00:36:33 +0000722 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner94908bb2010-08-18 21:23:25 +0000723 const char *env_encoding = Py_GETENV("PYTHONFSENCODING");
724 if (env_encoding != NULL) {
725 codeset = get_codec_name(env_encoding);
726 if (!codeset) {
727 fprintf(stderr, "PYTHONFSENCODING is not a valid encoding:\n");
728 PyErr_Print();
729 }
730 }
731 if (!codeset) {
732 /* On Unix, set the file system encoding according to the
733 user's preference, if the CODESET names a well-known
734 Python codec, and Py_FileSystemDefaultEncoding isn't
735 initialized by other means. Also set the encoding of
736 stdin and stdout if these are terminals. */
737 codeset = get_codeset();
738 }
Victor Stinner7f84ab52010-06-11 00:36:33 +0000739 if (codeset != NULL) {
740 Py_FileSystemDefaultEncoding = codeset;
741 Py_HasFileSystemDefaultEncoding = 0;
742 return;
Victor Stinner94908bb2010-08-18 21:23:25 +0000743 } else {
744 fprintf(stderr, "Unable to get the locale encoding:\n");
745 PyErr_Print();
Victor Stinner7f84ab52010-06-11 00:36:33 +0000746 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000747
Victor Stinner94908bb2010-08-18 21:23:25 +0000748 fprintf(stderr, "Unable to get the filesystem encoding: fallback to utf-8\n");
Victor Stinner7f84ab52010-06-11 00:36:33 +0000749 Py_FileSystemDefaultEncoding = "utf-8";
750 Py_HasFileSystemDefaultEncoding = 1;
751 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000752#endif
753
754 /* the encoding is mbcs, utf-8 or ascii */
755 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
756 if (!codec) {
757 /* Such error can only occurs in critical situations: no more
758 * memory, import a module of the standard library failed,
759 * etc. */
760 Py_FatalError("Py_Initialize: unable to load the file system codec");
761 } else {
762 Py_DECREF(codec);
763 }
764}
765
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000766/* Import the site module (not into __main__ though) */
767
768static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000769initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 PyObject *m;
772 m = PyImport_ImportModule("site");
773 if (m == NULL) {
774 PyErr_Print();
775 Py_Finalize();
776 exit(1);
777 }
778 else {
779 Py_DECREF(m);
780 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000781}
782
Antoine Pitrou05608432009-01-09 18:53:14 +0000783static PyObject*
784create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 int fd, int write_mode, char* name,
786 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
789 const char* mode;
790 PyObject *line_buffering;
791 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 /* stdin is always opened in buffered mode, first because it shouldn't
794 make a difference in common use cases, second because TextIOWrapper
795 depends on the presence of a read1() method which only exists on
796 buffered streams.
797 */
798 if (Py_UnbufferedStdioFlag && write_mode)
799 buffering = 0;
800 else
801 buffering = -1;
802 if (write_mode)
803 mode = "wb";
804 else
805 mode = "rb";
806 buf = PyObject_CallMethod(io, "open", "isiOOOi",
807 fd, mode, buffering,
808 Py_None, Py_None, Py_None, 0);
809 if (buf == NULL)
810 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (buffering) {
813 raw = PyObject_GetAttrString(buf, "raw");
814 if (raw == NULL)
815 goto error;
816 }
817 else {
818 raw = buf;
819 Py_INCREF(raw);
820 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 text = PyUnicode_FromString(name);
823 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
824 goto error;
825 res = PyObject_CallMethod(raw, "isatty", "");
826 if (res == NULL)
827 goto error;
828 isatty = PyObject_IsTrue(res);
829 Py_DECREF(res);
830 if (isatty == -1)
831 goto error;
832 if (isatty || Py_UnbufferedStdioFlag)
833 line_buffering = Py_True;
834 else
835 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 Py_CLEAR(raw);
838 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
841 buf, encoding, errors,
842 "\n", line_buffering);
843 Py_CLEAR(buf);
844 if (stream == NULL)
845 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (write_mode)
848 mode = "w";
849 else
850 mode = "r";
851 text = PyUnicode_FromString(mode);
852 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
853 goto error;
854 Py_CLEAR(text);
855 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000856
857error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 Py_XDECREF(buf);
859 Py_XDECREF(stream);
860 Py_XDECREF(text);
861 Py_XDECREF(raw);
862 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000863}
864
Georg Brandl1a3284e2007-12-02 09:40:06 +0000865/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000866static int
867initstdio(void)
868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyObject *iomod = NULL, *wrapper;
870 PyObject *bimod = NULL;
871 PyObject *m;
872 PyObject *std = NULL;
873 int status = 0, fd;
874 PyObject * encoding_attr;
875 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Hack to avoid a nasty recursion issue when Python is invoked
878 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
879 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
880 goto error;
881 }
882 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
885 goto error;
886 }
887 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (!(bimod = PyImport_ImportModule("builtins"))) {
890 goto error;
891 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 if (!(iomod = PyImport_ImportModule("io"))) {
894 goto error;
895 }
896 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
897 goto error;
898 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 /* Set builtins.open */
901 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
902 goto error;
903 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 encoding = Py_GETENV("PYTHONIOENCODING");
906 errors = NULL;
907 if (encoding) {
908 encoding = strdup(encoding);
909 errors = strchr(encoding, ':');
910 if (errors) {
911 *errors = '\0';
912 errors++;
913 }
914 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* Set sys.stdin */
917 fd = fileno(stdin);
918 /* Under some conditions stdin, stdout and stderr may not be connected
919 * and fileno() may point to an invalid file descriptor. For example
920 * GUI apps don't have valid standard streams by default.
921 */
922 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000923#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 std = Py_None;
925 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000926#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000928#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 }
930 else {
931 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
932 if (std == NULL)
933 goto error;
934 } /* if (fd < 0) */
935 PySys_SetObject("__stdin__", std);
936 PySys_SetObject("stdin", std);
937 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 /* Set sys.stdout */
940 fd = fileno(stdout);
941 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000942#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 std = Py_None;
944 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000945#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000947#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 }
949 else {
950 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
951 if (std == NULL)
952 goto error;
953 } /* if (fd < 0) */
954 PySys_SetObject("__stdout__", std);
955 PySys_SetObject("stdout", std);
956 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000957
Guido van Rossum98297ee2007-11-06 21:34:58 +0000958#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* Set sys.stderr, replaces the preliminary stderr */
960 fd = fileno(stderr);
961 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000962#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 std = Py_None;
964 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000965#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000967#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 }
969 else {
970 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
971 if (std == NULL)
972 goto error;
973 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 /* Same as hack above, pre-import stderr's codec to avoid recursion
976 when import.c tries to write to stderr in verbose mode. */
977 encoding_attr = PyObject_GetAttrString(std, "encoding");
978 if (encoding_attr != NULL) {
979 const char * encoding;
980 encoding = _PyUnicode_AsString(encoding_attr);
981 if (encoding != NULL) {
982 _PyCodec_Lookup(encoding);
983 }
984 }
985 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 PySys_SetObject("__stderr__", std);
988 PySys_SetObject("stderr", std);
989 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000990#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000993 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 status = -1;
995 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (encoding)
998 free(encoding);
999 Py_XDECREF(bimod);
1000 Py_XDECREF(iomod);
1001 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001002}
1003
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001004/* Parse input from a file and execute it */
1005
1006int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001007PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 if (filename == NULL)
1011 filename = "???";
1012 if (Py_FdIsInteractive(fp, filename)) {
1013 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1014 if (closeit)
1015 fclose(fp);
1016 return err;
1017 }
1018 else
1019 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001020}
1021
1022int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001023PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 PyObject *v;
1026 int ret;
1027 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001028
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (flags == NULL) {
1030 flags = &local_flags;
1031 local_flags.cf_flags = 0;
1032 }
1033 v = PySys_GetObject("ps1");
1034 if (v == NULL) {
1035 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1036 Py_XDECREF(v);
1037 }
1038 v = PySys_GetObject("ps2");
1039 if (v == NULL) {
1040 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1041 Py_XDECREF(v);
1042 }
1043 for (;;) {
1044 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1045 PRINT_TOTAL_REFS();
1046 if (ret == E_EOF)
1047 return 0;
1048 /*
1049 if (ret == E_NOMEM)
1050 return -1;
1051 */
1052 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001053}
1054
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001055/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001056static int PARSER_FLAGS(PyCompilerFlags *flags)
1057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 int parser_flags = 0;
1059 if (!flags)
1060 return 0;
1061 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1062 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1063 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1064 parser_flags |= PyPARSE_IGNORE_COOKIE;
1065 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1066 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1067 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001068}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001069
Thomas Wouters89f507f2006-12-13 04:49:30 +00001070#if 0
1071/* Keep an example of flags with future keyword support. */
1072#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1074 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1075 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1076 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001077#endif
1078
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001079int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001080PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 PyObject *m, *d, *v, *w, *oenc = NULL;
1083 mod_ty mod;
1084 PyArena *arena;
1085 char *ps1 = "", *ps2 = "", *enc = NULL;
1086 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 if (fp == stdin) {
1089 /* Fetch encoding from sys.stdin */
1090 v = PySys_GetObject("stdin");
1091 if (v == NULL || v == Py_None)
1092 return -1;
1093 oenc = PyObject_GetAttrString(v, "encoding");
1094 if (!oenc)
1095 return -1;
1096 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001097 if (enc == NULL)
1098 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 }
1100 v = PySys_GetObject("ps1");
1101 if (v != NULL) {
1102 v = PyObject_Str(v);
1103 if (v == NULL)
1104 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001105 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001107 if (ps1 == NULL) {
1108 PyErr_Clear();
1109 ps1 = "";
1110 }
1111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 }
1113 w = PySys_GetObject("ps2");
1114 if (w != NULL) {
1115 w = PyObject_Str(w);
1116 if (w == NULL)
1117 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001118 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001120 if (ps2 == NULL) {
1121 PyErr_Clear();
1122 ps2 = "";
1123 }
1124 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 }
1126 arena = PyArena_New();
1127 if (arena == NULL) {
1128 Py_XDECREF(v);
1129 Py_XDECREF(w);
1130 Py_XDECREF(oenc);
1131 return -1;
1132 }
1133 mod = PyParser_ASTFromFile(fp, filename, enc,
1134 Py_single_input, ps1, ps2,
1135 flags, &errcode, arena);
1136 Py_XDECREF(v);
1137 Py_XDECREF(w);
1138 Py_XDECREF(oenc);
1139 if (mod == NULL) {
1140 PyArena_Free(arena);
1141 if (errcode == E_EOF) {
1142 PyErr_Clear();
1143 return E_EOF;
1144 }
1145 PyErr_Print();
1146 return -1;
1147 }
1148 m = PyImport_AddModule("__main__");
1149 if (m == NULL) {
1150 PyArena_Free(arena);
1151 return -1;
1152 }
1153 d = PyModule_GetDict(m);
1154 v = run_mod(mod, filename, d, d, flags, arena);
1155 PyArena_Free(arena);
1156 flush_io();
1157 if (v == NULL) {
1158 PyErr_Print();
1159 return -1;
1160 }
1161 Py_DECREF(v);
1162 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001163}
1164
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001165/* Check whether a file maybe a pyc file: Look at the extension,
1166 the file type, and, if we may close it, at the first few bytes. */
1167
1168static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001169maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1172 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 /* Only look into the file if we are allowed to close it, since
1175 it then should also be seekable. */
1176 if (closeit) {
1177 /* Read only two bytes of the magic. If the file was opened in
1178 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1179 be read as they are on disk. */
1180 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1181 unsigned char buf[2];
1182 /* Mess: In case of -x, the stream is NOT at its start now,
1183 and ungetc() was used to push back the first newline,
1184 which makes the current stream position formally undefined,
1185 and a x-platform nightmare.
1186 Unfortunately, we have no direct way to know whether -x
1187 was specified. So we use a terrible hack: if the current
1188 stream position is not 0, we assume -x was specified, and
1189 give up. Bug 132850 on SourceForge spells out the
1190 hopelessness of trying anything else (fseek and ftell
1191 don't work predictably x-platform for text-mode files).
1192 */
1193 int ispyc = 0;
1194 if (ftell(fp) == 0) {
1195 if (fread(buf, 1, 2, fp) == 2 &&
1196 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1197 ispyc = 1;
1198 rewind(fp);
1199 }
1200 return ispyc;
1201 }
1202 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001203}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001204
Guido van Rossum0df002c2000-08-27 19:21:52 +00001205int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001206PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 PyObject *m, *d, *v;
1210 const char *ext;
1211 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 m = PyImport_AddModule("__main__");
1214 if (m == NULL)
1215 return -1;
1216 d = PyModule_GetDict(m);
1217 if (PyDict_GetItemString(d, "__file__") == NULL) {
1218 PyObject *f;
Victor Stinner0fe25a42010-06-17 23:08:50 +00001219 f = PyUnicode_FromString(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (f == NULL)
1221 return -1;
1222 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1223 Py_DECREF(f);
1224 return -1;
1225 }
1226 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1227 return -1;
1228 set_file_name = 1;
1229 Py_DECREF(f);
1230 }
1231 len = strlen(filename);
1232 ext = filename + len - (len > 4 ? 4 : 0);
1233 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1234 /* Try to run a pyc file. First, re-open in binary */
1235 if (closeit)
1236 fclose(fp);
1237 if ((fp = fopen(filename, "rb")) == NULL) {
1238 fprintf(stderr, "python: Can't reopen .pyc file\n");
1239 ret = -1;
1240 goto done;
1241 }
1242 /* Turn on optimization if a .pyo file is given */
1243 if (strcmp(ext, ".pyo") == 0)
1244 Py_OptimizeFlag = 1;
1245 v = run_pyc_file(fp, filename, d, d, flags);
1246 } else {
1247 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1248 closeit, flags);
1249 }
1250 flush_io();
1251 if (v == NULL) {
1252 PyErr_Print();
1253 ret = -1;
1254 goto done;
1255 }
1256 Py_DECREF(v);
1257 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001258 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1260 PyErr_Clear();
1261 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001262}
1263
1264int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001265PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 PyObject *m, *d, *v;
1268 m = PyImport_AddModule("__main__");
1269 if (m == NULL)
1270 return -1;
1271 d = PyModule_GetDict(m);
1272 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1273 if (v == NULL) {
1274 PyErr_Print();
1275 return -1;
1276 }
1277 Py_DECREF(v);
1278 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001279}
1280
Barry Warsaw035574d1997-08-29 22:07:17 +00001281static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001282parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 long hold;
1286 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 /* old style errors */
1289 if (PyTuple_Check(err))
1290 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1291 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (! (v = PyObject_GetAttrString(err, "msg")))
1296 goto finally;
1297 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 if (!(v = PyObject_GetAttrString(err, "filename")))
1300 goto finally;
1301 if (v == Py_None)
1302 *filename = NULL;
1303 else if (! (*filename = _PyUnicode_AsString(v)))
1304 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 Py_DECREF(v);
1307 if (!(v = PyObject_GetAttrString(err, "lineno")))
1308 goto finally;
1309 hold = PyLong_AsLong(v);
1310 Py_DECREF(v);
1311 v = NULL;
1312 if (hold < 0 && PyErr_Occurred())
1313 goto finally;
1314 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (!(v = PyObject_GetAttrString(err, "offset")))
1317 goto finally;
1318 if (v == Py_None) {
1319 *offset = -1;
1320 Py_DECREF(v);
1321 v = NULL;
1322 } else {
1323 hold = PyLong_AsLong(v);
1324 Py_DECREF(v);
1325 v = NULL;
1326 if (hold < 0 && PyErr_Occurred())
1327 goto finally;
1328 *offset = (int)hold;
1329 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 if (!(v = PyObject_GetAttrString(err, "text")))
1332 goto finally;
1333 if (v == Py_None)
1334 *text = NULL;
1335 else if (!PyUnicode_Check(v) ||
1336 !(*text = _PyUnicode_AsString(v)))
1337 goto finally;
1338 Py_DECREF(v);
1339 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001340
1341finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 Py_XDECREF(v);
1343 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001344}
1345
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001346void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001347PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001350}
1351
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001352static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001353print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 char *nl;
1356 if (offset >= 0) {
1357 if (offset > 0 && offset == (int)strlen(text))
1358 offset--;
1359 for (;;) {
1360 nl = strchr(text, '\n');
1361 if (nl == NULL || nl-text >= offset)
1362 break;
1363 offset -= (int)(nl+1-text);
1364 text = nl+1;
1365 }
1366 while (*text == ' ' || *text == '\t') {
1367 text++;
1368 offset--;
1369 }
1370 }
1371 PyFile_WriteString(" ", f);
1372 PyFile_WriteString(text, f);
1373 if (*text == '\0' || text[strlen(text)-1] != '\n')
1374 PyFile_WriteString("\n", f);
1375 if (offset == -1)
1376 return;
1377 PyFile_WriteString(" ", f);
1378 offset--;
1379 while (offset > 0) {
1380 PyFile_WriteString(" ", f);
1381 offset--;
1382 }
1383 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001384}
1385
Guido van Rossum66e8e862001-03-23 17:54:43 +00001386static void
1387handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyObject *exception, *value, *tb;
1390 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (Py_InspectFlag)
1393 /* Don't exit if -i flag was given. This flag is set to 0
1394 * when entering interactive mode for inspecting. */
1395 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 PyErr_Fetch(&exception, &value, &tb);
1398 fflush(stdout);
1399 if (value == NULL || value == Py_None)
1400 goto done;
1401 if (PyExceptionInstance_Check(value)) {
1402 /* The error code should be in the `code' attribute. */
1403 PyObject *code = PyObject_GetAttrString(value, "code");
1404 if (code) {
1405 Py_DECREF(value);
1406 value = code;
1407 if (value == Py_None)
1408 goto done;
1409 }
1410 /* If we failed to dig out the 'code' attribute,
1411 just let the else clause below print the error. */
1412 }
1413 if (PyLong_Check(value))
1414 exitcode = (int)PyLong_AsLong(value);
1415 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001416 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001417 if (sys_stderr != NULL && sys_stderr != Py_None) {
1418 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1419 } else {
1420 PyObject_Print(value, stderr, Py_PRINT_RAW);
1421 fflush(stderr);
1422 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 PySys_WriteStderr("\n");
1424 exitcode = 1;
1425 }
Tim Peterscf615b52003-04-19 18:47:02 +00001426 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 /* Restore and clear the exception info, in order to properly decref
1428 * the exception, value, and traceback. If we just exit instead,
1429 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1430 * some finalizers from running.
1431 */
1432 PyErr_Restore(exception, value, tb);
1433 PyErr_Clear();
1434 Py_Exit(exitcode);
1435 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001436}
1437
1438void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001439PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1444 handle_system_exit();
1445 }
1446 PyErr_Fetch(&exception, &v, &tb);
1447 if (exception == NULL)
1448 return;
1449 PyErr_NormalizeException(&exception, &v, &tb);
1450 if (tb == NULL) {
1451 tb = Py_None;
1452 Py_INCREF(tb);
1453 }
1454 PyException_SetTraceback(v, tb);
1455 if (exception == NULL)
1456 return;
1457 /* Now we know v != NULL too */
1458 if (set_sys_last_vars) {
1459 PySys_SetObject("last_type", exception);
1460 PySys_SetObject("last_value", v);
1461 PySys_SetObject("last_traceback", tb);
1462 }
1463 hook = PySys_GetObject("excepthook");
1464 if (hook) {
1465 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1466 PyObject *result = PyEval_CallObject(hook, args);
1467 if (result == NULL) {
1468 PyObject *exception2, *v2, *tb2;
1469 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1470 handle_system_exit();
1471 }
1472 PyErr_Fetch(&exception2, &v2, &tb2);
1473 PyErr_NormalizeException(&exception2, &v2, &tb2);
1474 /* It should not be possible for exception2 or v2
1475 to be NULL. However PyErr_Display() can't
1476 tolerate NULLs, so just be safe. */
1477 if (exception2 == NULL) {
1478 exception2 = Py_None;
1479 Py_INCREF(exception2);
1480 }
1481 if (v2 == NULL) {
1482 v2 = Py_None;
1483 Py_INCREF(v2);
1484 }
1485 fflush(stdout);
1486 PySys_WriteStderr("Error in sys.excepthook:\n");
1487 PyErr_Display(exception2, v2, tb2);
1488 PySys_WriteStderr("\nOriginal exception was:\n");
1489 PyErr_Display(exception, v, tb);
1490 Py_DECREF(exception2);
1491 Py_DECREF(v2);
1492 Py_XDECREF(tb2);
1493 }
1494 Py_XDECREF(result);
1495 Py_XDECREF(args);
1496 } else {
1497 PySys_WriteStderr("sys.excepthook is missing\n");
1498 PyErr_Display(exception, v, tb);
1499 }
1500 Py_XDECREF(exception);
1501 Py_XDECREF(v);
1502 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001503}
1504
Benjamin Petersone6528212008-07-15 15:32:09 +00001505static void
1506print_exception(PyObject *f, PyObject *value)
1507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 int err = 0;
1509 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 if (!PyExceptionInstance_Check(value)) {
1512 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1513 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1514 PyFile_WriteString(" found\n", f);
1515 return;
1516 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 Py_INCREF(value);
1519 fflush(stdout);
1520 type = (PyObject *) Py_TYPE(value);
1521 tb = PyException_GetTraceback(value);
1522 if (tb && tb != Py_None)
1523 err = PyTraceBack_Print(tb, f);
1524 if (err == 0 &&
1525 PyObject_HasAttrString(value, "print_file_and_line"))
1526 {
1527 PyObject *message;
1528 const char *filename, *text;
1529 int lineno, offset;
1530 if (!parse_syntax_error(value, &message, &filename,
1531 &lineno, &offset, &text))
1532 PyErr_Clear();
1533 else {
1534 char buf[10];
1535 PyFile_WriteString(" File \"", f);
1536 if (filename == NULL)
1537 PyFile_WriteString("<string>", f);
1538 else
1539 PyFile_WriteString(filename, f);
1540 PyFile_WriteString("\", line ", f);
1541 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1542 PyFile_WriteString(buf, f);
1543 PyFile_WriteString("\n", f);
1544 if (text != NULL)
1545 print_error_text(f, offset, text);
1546 Py_DECREF(value);
1547 value = message;
1548 /* Can't be bothered to check all those
1549 PyFile_WriteString() calls */
1550 if (PyErr_Occurred())
1551 err = -1;
1552 }
1553 }
1554 if (err) {
1555 /* Don't do anything else */
1556 }
1557 else {
1558 PyObject* moduleName;
1559 char* className;
1560 assert(PyExceptionClass_Check(type));
1561 className = PyExceptionClass_Name(type);
1562 if (className != NULL) {
1563 char *dot = strrchr(className, '.');
1564 if (dot != NULL)
1565 className = dot+1;
1566 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 moduleName = PyObject_GetAttrString(type, "__module__");
1569 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1570 {
1571 Py_DECREF(moduleName);
1572 err = PyFile_WriteString("<unknown>", f);
1573 }
1574 else {
1575 char* modstr = _PyUnicode_AsString(moduleName);
1576 if (modstr && strcmp(modstr, "builtins"))
1577 {
1578 err = PyFile_WriteString(modstr, f);
1579 err += PyFile_WriteString(".", f);
1580 }
1581 Py_DECREF(moduleName);
1582 }
1583 if (err == 0) {
1584 if (className == NULL)
1585 err = PyFile_WriteString("<unknown>", f);
1586 else
1587 err = PyFile_WriteString(className, f);
1588 }
1589 }
1590 if (err == 0 && (value != Py_None)) {
1591 PyObject *s = PyObject_Str(value);
1592 /* only print colon if the str() of the
1593 object is not the empty string
1594 */
1595 if (s == NULL)
1596 err = -1;
1597 else if (!PyUnicode_Check(s) ||
1598 PyUnicode_GetSize(s) != 0)
1599 err = PyFile_WriteString(": ", f);
1600 if (err == 0)
1601 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1602 Py_XDECREF(s);
1603 }
1604 /* try to write a newline in any case */
1605 err += PyFile_WriteString("\n", f);
1606 Py_XDECREF(tb);
1607 Py_DECREF(value);
1608 /* If an error happened here, don't show it.
1609 XXX This is wrong, but too many callers rely on this behavior. */
1610 if (err != 0)
1611 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001612}
1613
1614static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 "\nThe above exception was the direct cause "
1616 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001617
1618static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 "\nDuring handling of the above exception, "
1620 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001621
1622static void
1623print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 int err = 0, res;
1626 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (seen != NULL) {
1629 /* Exception chaining */
1630 if (PySet_Add(seen, value) == -1)
1631 PyErr_Clear();
1632 else if (PyExceptionInstance_Check(value)) {
1633 cause = PyException_GetCause(value);
1634 context = PyException_GetContext(value);
1635 if (cause) {
1636 res = PySet_Contains(seen, cause);
1637 if (res == -1)
1638 PyErr_Clear();
1639 if (res == 0) {
1640 print_exception_recursive(
1641 f, cause, seen);
1642 err |= PyFile_WriteString(
1643 cause_message, f);
1644 }
1645 }
1646 else if (context) {
1647 res = PySet_Contains(seen, context);
1648 if (res == -1)
1649 PyErr_Clear();
1650 if (res == 0) {
1651 print_exception_recursive(
1652 f, context, seen);
1653 err |= PyFile_WriteString(
1654 context_message, f);
1655 }
1656 }
1657 Py_XDECREF(context);
1658 Py_XDECREF(cause);
1659 }
1660 }
1661 print_exception(f, value);
1662 if (err != 0)
1663 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001664}
1665
Thomas Wouters477c8d52006-05-27 19:21:47 +00001666void
1667PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 PyObject *seen;
1670 PyObject *f = PySys_GetObject("stderr");
1671 if (f == Py_None) {
1672 /* pass */
1673 }
1674 else if (f == NULL) {
1675 _PyObject_Dump(value);
1676 fprintf(stderr, "lost sys.stderr\n");
1677 }
1678 else {
1679 /* We choose to ignore seen being possibly NULL, and report
1680 at least the main exception (it could be a MemoryError).
1681 */
1682 seen = PySet_New(NULL);
1683 if (seen == NULL)
1684 PyErr_Clear();
1685 print_exception_recursive(f, value, seen);
1686 Py_XDECREF(seen);
1687 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001688}
1689
Guido van Rossum82598051997-03-05 00:20:32 +00001690PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001691PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyObject *ret = NULL;
1695 mod_ty mod;
1696 PyArena *arena = PyArena_New();
1697 if (arena == NULL)
1698 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1701 if (mod != NULL)
1702 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1703 PyArena_Free(arena);
1704 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001705}
1706
1707PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001708PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 PyObject *ret;
1712 mod_ty mod;
1713 PyArena *arena = PyArena_New();
1714 if (arena == NULL)
1715 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1718 flags, NULL, arena);
1719 if (closeit)
1720 fclose(fp);
1721 if (mod == NULL) {
1722 PyArena_Free(arena);
1723 return NULL;
1724 }
1725 ret = run_mod(mod, filename, globals, locals, flags, arena);
1726 PyArena_Free(arena);
1727 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001728}
1729
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001730static void
1731flush_io(void)
1732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 PyObject *f, *r;
1734 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 /* Save the current exception */
1737 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 f = PySys_GetObject("stderr");
1740 if (f != NULL) {
1741 r = PyObject_CallMethod(f, "flush", "");
1742 if (r)
1743 Py_DECREF(r);
1744 else
1745 PyErr_Clear();
1746 }
1747 f = PySys_GetObject("stdout");
1748 if (f != NULL) {
1749 r = PyObject_CallMethod(f, "flush", "");
1750 if (r)
1751 Py_DECREF(r);
1752 else
1753 PyErr_Clear();
1754 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001756 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001757}
1758
Guido van Rossum82598051997-03-05 00:20:32 +00001759static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001760run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 PyCodeObject *co;
1764 PyObject *v;
1765 co = PyAST_Compile(mod, filename, flags, arena);
1766 if (co == NULL)
1767 return NULL;
1768 v = PyEval_EvalCode(co, globals, locals);
1769 Py_DECREF(co);
1770 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001771}
1772
Guido van Rossum82598051997-03-05 00:20:32 +00001773static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001774run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 PyCodeObject *co;
1778 PyObject *v;
1779 long magic;
1780 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 magic = PyMarshal_ReadLongFromFile(fp);
1783 if (magic != PyImport_GetMagicNumber()) {
1784 PyErr_SetString(PyExc_RuntimeError,
1785 "Bad magic number in .pyc file");
1786 return NULL;
1787 }
1788 (void) PyMarshal_ReadLongFromFile(fp);
1789 v = PyMarshal_ReadLastObjectFromFile(fp);
1790 fclose(fp);
1791 if (v == NULL || !PyCode_Check(v)) {
1792 Py_XDECREF(v);
1793 PyErr_SetString(PyExc_RuntimeError,
1794 "Bad code object in .pyc file");
1795 return NULL;
1796 }
1797 co = (PyCodeObject *)v;
1798 v = PyEval_EvalCode(co, globals, locals);
1799 if (v && flags)
1800 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1801 Py_DECREF(co);
1802 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001803}
1804
Guido van Rossum82598051997-03-05 00:20:32 +00001805PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001806Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 PyCodeObject *co;
1810 mod_ty mod;
1811 PyArena *arena = PyArena_New();
1812 if (arena == NULL)
1813 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1816 if (mod == NULL) {
1817 PyArena_Free(arena);
1818 return NULL;
1819 }
1820 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1821 PyObject *result = PyAST_mod2obj(mod);
1822 PyArena_Free(arena);
1823 return result;
1824 }
1825 co = PyAST_Compile(mod, filename, flags, arena);
1826 PyArena_Free(arena);
1827 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001828}
1829
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001830struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001831Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 struct symtable *st;
1834 mod_ty mod;
1835 PyCompilerFlags flags;
1836 PyArena *arena = PyArena_New();
1837 if (arena == NULL)
1838 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 flags.cf_flags = 0;
1841 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1842 if (mod == NULL) {
1843 PyArena_Free(arena);
1844 return NULL;
1845 }
1846 st = PySymtable_Build(mod, filename, 0);
1847 PyArena_Free(arena);
1848 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001849}
1850
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001851/* Preferred access to parser is through AST. */
1852mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001853PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 mod_ty mod;
1857 PyCompilerFlags localflags;
1858 perrdetail err;
1859 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1862 &_PyParser_Grammar, start, &err,
1863 &iflags);
1864 if (flags == NULL) {
1865 localflags.cf_flags = 0;
1866 flags = &localflags;
1867 }
1868 if (n) {
1869 flags->cf_flags |= iflags & PyCF_MASK;
1870 mod = PyAST_FromNode(n, flags, filename, arena);
1871 PyNode_Free(n);
1872 return mod;
1873 }
1874 else {
1875 err_input(&err);
1876 return NULL;
1877 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001878}
1879
1880mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001881PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 int start, char *ps1,
1883 char *ps2, PyCompilerFlags *flags, int *errcode,
1884 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 mod_ty mod;
1887 PyCompilerFlags localflags;
1888 perrdetail err;
1889 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1892 &_PyParser_Grammar,
1893 start, ps1, ps2, &err, &iflags);
1894 if (flags == NULL) {
1895 localflags.cf_flags = 0;
1896 flags = &localflags;
1897 }
1898 if (n) {
1899 flags->cf_flags |= iflags & PyCF_MASK;
1900 mod = PyAST_FromNode(n, flags, filename, arena);
1901 PyNode_Free(n);
1902 return mod;
1903 }
1904 else {
1905 err_input(&err);
1906 if (errcode)
1907 *errcode = err.error;
1908 return NULL;
1909 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001910}
1911
Guido van Rossuma110aa61994-08-29 12:50:44 +00001912/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001913
Guido van Rossuma110aa61994-08-29 12:50:44 +00001914node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001915PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 perrdetail err;
1918 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1919 &_PyParser_Grammar,
1920 start, NULL, NULL, &err, flags);
1921 if (n == NULL)
1922 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001925}
1926
Guido van Rossuma110aa61994-08-29 12:50:44 +00001927/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001928
Guido van Rossuma110aa61994-08-29 12:50:44 +00001929node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001930PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 perrdetail err;
1933 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1934 start, &err, flags);
1935 if (n == NULL)
1936 err_input(&err);
1937 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001938}
1939
1940node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001941PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 perrdetail err;
1945 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1946 &_PyParser_Grammar, start, &err, flags);
1947 if (n == NULL)
1948 err_input(&err);
1949 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001950}
1951
1952node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001953PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001956}
1957
Guido van Rossum66ebd912003-04-17 16:02:26 +00001958/* May want to move a more generalized form of this to parsetok.c or
1959 even parser modules. */
1960
1961void
1962PyParser_SetError(perrdetail *err)
1963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001965}
1966
Guido van Rossuma110aa61994-08-29 12:50:44 +00001967/* Set the error appropriate to the given input error code (see errcode.h) */
1968
1969static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001970err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 PyObject *v, *w, *errtype, *errtext;
1973 PyObject *msg_obj = NULL;
1974 char *msg = NULL;
1975 errtype = PyExc_SyntaxError;
1976 switch (err->error) {
1977 case E_ERROR:
1978 return;
1979 case E_SYNTAX:
1980 errtype = PyExc_IndentationError;
1981 if (err->expected == INDENT)
1982 msg = "expected an indented block";
1983 else if (err->token == INDENT)
1984 msg = "unexpected indent";
1985 else if (err->token == DEDENT)
1986 msg = "unexpected unindent";
1987 else {
1988 errtype = PyExc_SyntaxError;
1989 msg = "invalid syntax";
1990 }
1991 break;
1992 case E_TOKEN:
1993 msg = "invalid token";
1994 break;
1995 case E_EOFS:
1996 msg = "EOF while scanning triple-quoted string literal";
1997 break;
1998 case E_EOLS:
1999 msg = "EOL while scanning string literal";
2000 break;
2001 case E_INTR:
2002 if (!PyErr_Occurred())
2003 PyErr_SetNone(PyExc_KeyboardInterrupt);
2004 goto cleanup;
2005 case E_NOMEM:
2006 PyErr_NoMemory();
2007 goto cleanup;
2008 case E_EOF:
2009 msg = "unexpected EOF while parsing";
2010 break;
2011 case E_TABSPACE:
2012 errtype = PyExc_TabError;
2013 msg = "inconsistent use of tabs and spaces in indentation";
2014 break;
2015 case E_OVERFLOW:
2016 msg = "expression too long";
2017 break;
2018 case E_DEDENT:
2019 errtype = PyExc_IndentationError;
2020 msg = "unindent does not match any outer indentation level";
2021 break;
2022 case E_TOODEEP:
2023 errtype = PyExc_IndentationError;
2024 msg = "too many levels of indentation";
2025 break;
2026 case E_DECODE: {
2027 PyObject *type, *value, *tb;
2028 PyErr_Fetch(&type, &value, &tb);
2029 msg = "unknown decode error";
2030 if (value != NULL)
2031 msg_obj = PyObject_Str(value);
2032 Py_XDECREF(type);
2033 Py_XDECREF(value);
2034 Py_XDECREF(tb);
2035 break;
2036 }
2037 case E_LINECONT:
2038 msg = "unexpected character after line continuation character";
2039 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 case E_IDENTIFIER:
2042 msg = "invalid character in identifier";
2043 break;
2044 default:
2045 fprintf(stderr, "error=%d\n", err->error);
2046 msg = "unknown parsing error";
2047 break;
2048 }
2049 /* err->text may not be UTF-8 in case of decoding errors.
2050 Explicitly convert to an object. */
2051 if (!err->text) {
2052 errtext = Py_None;
2053 Py_INCREF(Py_None);
2054 } else {
2055 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2056 "replace");
2057 }
2058 v = Py_BuildValue("(ziiN)", err->filename,
2059 err->lineno, err->offset, errtext);
2060 if (v != NULL) {
2061 if (msg_obj)
2062 w = Py_BuildValue("(OO)", msg_obj, v);
2063 else
2064 w = Py_BuildValue("(sO)", msg, v);
2065 } else
2066 w = NULL;
2067 Py_XDECREF(v);
2068 PyErr_SetObject(errtype, w);
2069 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002070cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 Py_XDECREF(msg_obj);
2072 if (err->text != NULL) {
2073 PyObject_FREE(err->text);
2074 err->text = NULL;
2075 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002076}
2077
2078/* Print fatal error message and abort */
2079
2080void
Tim Peters7c321a82002-07-09 02:57:01 +00002081Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 fprintf(stderr, "Fatal Python error: %s\n", msg);
2084 fflush(stderr); /* it helps in Windows debug build */
2085 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002086 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002088#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 {
2090 size_t len = strlen(msg);
2091 WCHAR* buffer;
2092 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 /* Convert the message to wchar_t. This uses a simple one-to-one
2095 conversion, assuming that the this error message actually uses ASCII
2096 only. If this ceases to be true, we will have to convert. */
2097 buffer = alloca( (len+1) * (sizeof *buffer));
2098 for( i=0; i<=len; ++i)
2099 buffer[i] = msg[i];
2100 OutputDebugStringW(L"Fatal Python error: ");
2101 OutputDebugStringW(buffer);
2102 OutputDebugStringW(L"\n");
2103 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002104#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002106#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002107#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002109}
2110
2111/* Clean up and exit */
2112
Guido van Rossuma110aa61994-08-29 12:50:44 +00002113#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002114#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002115#endif
2116
Collin Winter670e6922007-03-21 02:57:17 +00002117static void (*pyexitfunc)(void) = NULL;
2118/* For the atexit module. */
2119void _Py_PyAtExit(void (*func)(void))
2120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002122}
2123
2124static void
2125call_py_exitfuncs(void)
2126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (pyexitfunc == NULL)
2128 return;
Collin Winter670e6922007-03-21 02:57:17 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 (*pyexitfunc)();
2131 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002132}
2133
Antoine Pitrou011bd622009-10-20 21:52:47 +00002134/* Wait until threading._shutdown completes, provided
2135 the threading module was imported in the first place.
2136 The shutdown routine will wait until all non-daemon
2137 "threading" threads have completed. */
2138static void
2139wait_for_thread_shutdown(void)
2140{
2141#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 PyObject *result;
2143 PyThreadState *tstate = PyThreadState_GET();
2144 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2145 "threading");
2146 if (threading == NULL) {
2147 /* threading not imported */
2148 PyErr_Clear();
2149 return;
2150 }
2151 result = PyObject_CallMethod(threading, "_shutdown", "");
2152 if (result == NULL) {
2153 PyErr_WriteUnraisable(threading);
2154 }
2155 else {
2156 Py_DECREF(result);
2157 }
2158 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002159#endif
2160}
2161
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002162#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002163static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002164static int nexitfuncs = 0;
2165
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002166int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 if (nexitfuncs >= NEXITFUNCS)
2169 return -1;
2170 exitfuncs[nexitfuncs++] = func;
2171 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002172}
2173
Guido van Rossumcc283f51997-08-05 02:22:03 +00002174static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002175call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 while (nexitfuncs > 0)
2178 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 fflush(stdout);
2181 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002182}
2183
2184void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002185Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002190}
2191
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002192static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002193initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002194{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002195#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002197#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002198#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002200#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002201#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002203#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002205}
2206
Guido van Rossum7433b121997-02-14 19:45:36 +00002207
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002208/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2209 *
2210 * All of the code in this function must only use async-signal-safe functions,
2211 * listed at `man 7 signal` or
2212 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2213 */
2214void
2215_Py_RestoreSignals(void)
2216{
2217#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002219#endif
2220#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002222#endif
2223#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002225#endif
2226}
2227
2228
Guido van Rossum7433b121997-02-14 19:45:36 +00002229/*
2230 * The file descriptor fd is considered ``interactive'' if either
2231 * a) isatty(fd) is TRUE, or
2232 * b) the -i flag was given, and the filename associated with
2233 * the descriptor is NULL or "<stdin>" or "???".
2234 */
2235int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002236Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 if (isatty((int)fileno(fp)))
2239 return 1;
2240 if (!Py_InteractiveFlag)
2241 return 0;
2242 return (filename == NULL) ||
2243 (strcmp(filename, "<stdin>") == 0) ||
2244 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002245}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002246
2247
Tim Petersd08e3822003-04-17 15:24:21 +00002248#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002249#if defined(WIN32) && defined(_MSC_VER)
2250
2251/* Stack checking for Microsoft C */
2252
2253#include <malloc.h>
2254#include <excpt.h>
2255
Fred Drakee8de31c2000-08-31 05:38:39 +00002256/*
2257 * Return non-zero when we run out of memory on the stack; zero otherwise.
2258 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002259int
Fred Drake399739f2000-08-31 05:52:44 +00002260PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 __try {
2263 /* alloca throws a stack overflow exception if there's
2264 not enough space left on the stack */
2265 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2266 return 0;
2267 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2268 EXCEPTION_EXECUTE_HANDLER :
2269 EXCEPTION_CONTINUE_SEARCH) {
2270 int errcode = _resetstkoflw();
2271 if (errcode == 0)
2272 {
2273 Py_FatalError("Could not reset the stack!");
2274 }
2275 }
2276 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002277}
2278
2279#endif /* WIN32 && _MSC_VER */
2280
2281/* Alternate implementations can be added here... */
2282
2283#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002284
2285
2286/* Wrappers around sigaction() or signal(). */
2287
2288PyOS_sighandler_t
2289PyOS_getsig(int sig)
2290{
2291#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 struct sigaction context;
2293 if (sigaction(sig, NULL, &context) == -1)
2294 return SIG_ERR;
2295 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002296#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002298/* Special signal handling for the secure CRT in Visual Studio 2005 */
2299#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 switch (sig) {
2301 /* Only these signals are valid */
2302 case SIGINT:
2303 case SIGILL:
2304 case SIGFPE:
2305 case SIGSEGV:
2306 case SIGTERM:
2307 case SIGBREAK:
2308 case SIGABRT:
2309 break;
2310 /* Don't call signal() with other values or it will assert */
2311 default:
2312 return SIG_ERR;
2313 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002314#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 handler = signal(sig, SIG_IGN);
2316 if (handler != SIG_ERR)
2317 signal(sig, handler);
2318 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002319#endif
2320}
2321
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002322/*
2323 * All of the code in this function must only use async-signal-safe functions,
2324 * listed at `man 7 signal` or
2325 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2326 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002327PyOS_sighandler_t
2328PyOS_setsig(int sig, PyOS_sighandler_t handler)
2329{
2330#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 /* Some code in Modules/signalmodule.c depends on sigaction() being
2332 * used here if HAVE_SIGACTION is defined. Fix that if this code
2333 * changes to invalidate that assumption.
2334 */
2335 struct sigaction context, ocontext;
2336 context.sa_handler = handler;
2337 sigemptyset(&context.sa_mask);
2338 context.sa_flags = 0;
2339 if (sigaction(sig, &context, &ocontext) == -1)
2340 return SIG_ERR;
2341 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002342#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 PyOS_sighandler_t oldhandler;
2344 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002345#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002347#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002349#endif
2350}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002351
2352/* Deprecated C API functions still provided for binary compatiblity */
2353
2354#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002355PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002356PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002359}
2360
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002361#undef PyParser_SimpleParseString
2362PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363PyParser_SimpleParseString(const char *str, int start)
2364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002366}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002367
2368#undef PyRun_AnyFile
2369PyAPI_FUNC(int)
2370PyRun_AnyFile(FILE *fp, const char *name)
2371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002373}
2374
2375#undef PyRun_AnyFileEx
2376PyAPI_FUNC(int)
2377PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002380}
2381
2382#undef PyRun_AnyFileFlags
2383PyAPI_FUNC(int)
2384PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002387}
2388
2389#undef PyRun_File
2390PyAPI_FUNC(PyObject *)
2391PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002394}
2395
2396#undef PyRun_FileEx
2397PyAPI_FUNC(PyObject *)
2398PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002401}
2402
2403#undef PyRun_FileFlags
2404PyAPI_FUNC(PyObject *)
2405PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002409}
2410
2411#undef PyRun_SimpleFile
2412PyAPI_FUNC(int)
2413PyRun_SimpleFile(FILE *f, const char *p)
2414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002416}
2417
2418#undef PyRun_SimpleFileEx
2419PyAPI_FUNC(int)
2420PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002423}
2424
2425
2426#undef PyRun_String
2427PyAPI_FUNC(PyObject *)
2428PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002431}
2432
2433#undef PyRun_SimpleString
2434PyAPI_FUNC(int)
2435PyRun_SimpleString(const char *s)
2436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002438}
2439
2440#undef Py_CompileString
2441PyAPI_FUNC(PyObject *)
2442Py_CompileString(const char *str, const char *p, int s)
2443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002445}
2446
2447#undef PyRun_InteractiveOne
2448PyAPI_FUNC(int)
2449PyRun_InteractiveOne(FILE *f, const char *p)
2450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002452}
2453
2454#undef PyRun_InteractiveLoop
2455PyAPI_FUNC(int)
2456PyRun_InteractiveLoop(FILE *f, const char *p)
2457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002459}
2460
2461#ifdef __cplusplus
2462}
2463#endif