blob: 8f4e9f18f7e0409c801c00a320b902e0fc3404f3 [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
Antoine Pitrou1df15362010-09-13 14:16:46 +0000517#ifdef WITH_THREAD
518 _PyEval_FiniThreads();
519#endif
520
Tim Peters269b2a62003-04-17 19:52:29 +0000521#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 /* Display addresses (& refcnts) of all objects still alive.
523 * An address can be used to find the repr of the object, printed
524 * above by _Py_PrintReferences.
525 */
526 if (Py_GETENV("PYTHONDUMPREFS"))
527 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000528#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000529#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (Py_GETENV("PYTHONMALLOCSTATS"))
531 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000532#endif
533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000535}
536
537/* Create and initialize a new interpreter and thread, and return the
538 new thread. This requires that Py_Initialize() has been called
539 first.
540
541 Unsuccessful initialization yields a NULL pointer. Note that *no*
542 exception information is available even in this case -- the
543 exception information is held in the thread, and there is no
544 thread.
545
546 Locking: as above.
547
548*/
549
550PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000551Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 PyInterpreterState *interp;
554 PyThreadState *tstate, *save_tstate;
555 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (!initialized)
558 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 interp = PyInterpreterState_New();
561 if (interp == NULL)
562 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 tstate = PyThreadState_New(interp);
565 if (tstate == NULL) {
566 PyInterpreterState_Delete(interp);
567 return NULL;
568 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 interp->modules = PyDict_New();
575 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 bimod = _PyImport_FindExtension("builtins", "builtins");
578 if (bimod != NULL) {
579 interp->builtins = PyModule_GetDict(bimod);
580 if (interp->builtins == NULL)
581 goto handle_error;
582 Py_INCREF(interp->builtins);
583 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 /* initialize builtin exceptions */
586 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 sysmod = _PyImport_FindExtension("sys", "sys");
589 if (bimod != NULL && sysmod != NULL) {
590 PyObject *pstderr;
591 interp->sysdict = PyModule_GetDict(sysmod);
592 if (interp->sysdict == NULL)
593 goto handle_error;
594 Py_INCREF(interp->sysdict);
595 PySys_SetPath(Py_GetPath());
596 PyDict_SetItemString(interp->sysdict, "modules",
597 interp->modules);
598 /* Set up a preliminary stderr printer until we have enough
599 infrastructure for the io module in place. */
600 pstderr = PyFile_NewStdPrinter(fileno(stderr));
601 if (pstderr == NULL)
602 Py_FatalError("Py_Initialize: can't set preliminary stderr");
603 PySys_SetObject("stderr", pstderr);
604 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 _PyImportHooks_Init();
607 if (initstdio() < 0)
608 Py_FatalError(
609 "Py_Initialize: can't initialize sys standard streams");
610 initmain();
611 if (!Py_NoSiteFlag)
612 initsite();
613 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 if (!PyErr_Occurred())
616 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Thomas Wouters89f507f2006-12-13 04:49:30 +0000618handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 PyErr_Print();
622 PyThreadState_Clear(tstate);
623 PyThreadState_Swap(save_tstate);
624 PyThreadState_Delete(tstate);
625 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000628}
629
630/* Delete an interpreter and its last thread. This requires that the
631 given thread state is current, that the thread has no remaining
632 frames, and that it is its interpreter's only remaining thread.
633 It is a fatal error to violate these constraints.
634
635 (Py_Finalize() doesn't have these constraints -- it zaps
636 everything, regardless.)
637
638 Locking: as above.
639
640*/
641
642void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000643Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (tstate != PyThreadState_GET())
648 Py_FatalError("Py_EndInterpreter: thread is not current");
649 if (tstate->frame != NULL)
650 Py_FatalError("Py_EndInterpreter: thread still has a frame");
651 if (tstate != interp->tstate_head || tstate->next != NULL)
652 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyImport_Cleanup();
655 PyInterpreterState_Clear(interp);
656 PyThreadState_Swap(NULL);
657 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000658}
659
Martin v. Löwis790465f2008-04-05 20:41:37 +0000660static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000661
662void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000663Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (pn && *pn)
666 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000667}
668
Martin v. Löwis790465f2008-04-05 20:41:37 +0000669wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000670Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000673}
674
Martin v. Löwis790465f2008-04-05 20:41:37 +0000675static wchar_t *default_home = NULL;
676static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000677
678void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000679Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000682}
683
Martin v. Löwis790465f2008-04-05 20:41:37 +0000684wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000685Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 wchar_t *home = default_home;
688 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
689 char* chome = Py_GETENV("PYTHONHOME");
690 if (chome) {
691 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
692 if (r != (size_t)-1 && r <= PATH_MAX)
693 home = env_home;
694 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 }
697 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000698}
699
Guido van Rossum6135a871995-01-09 17:53:26 +0000700/* Create __main__ module */
701
702static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000703initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyObject *m, *d;
706 m = PyImport_AddModule("__main__");
707 if (m == NULL)
708 Py_FatalError("can't create __main__ module");
709 d = PyModule_GetDict(m);
710 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
711 PyObject *bimod = PyImport_ImportModule("builtins");
712 if (bimod == NULL ||
713 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
714 Py_FatalError("can't add __builtins__ to __main__");
715 Py_DECREF(bimod);
716 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000717}
718
Victor Stinnerb744ba12010-05-15 12:27:16 +0000719static void
720initfsencoding(void)
721{
722 PyObject *codec;
723#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000724 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000725
Victor Stinner7f84ab52010-06-11 00:36:33 +0000726 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner94908bb2010-08-18 21:23:25 +0000727 const char *env_encoding = Py_GETENV("PYTHONFSENCODING");
728 if (env_encoding != NULL) {
729 codeset = get_codec_name(env_encoding);
730 if (!codeset) {
731 fprintf(stderr, "PYTHONFSENCODING is not a valid encoding:\n");
732 PyErr_Print();
733 }
734 }
735 if (!codeset) {
736 /* On Unix, set the file system encoding according to the
737 user's preference, if the CODESET names a well-known
738 Python codec, and Py_FileSystemDefaultEncoding isn't
739 initialized by other means. Also set the encoding of
740 stdin and stdout if these are terminals. */
741 codeset = get_codeset();
742 }
Victor Stinner7f84ab52010-06-11 00:36:33 +0000743 if (codeset != NULL) {
744 Py_FileSystemDefaultEncoding = codeset;
745 Py_HasFileSystemDefaultEncoding = 0;
746 return;
Victor Stinner94908bb2010-08-18 21:23:25 +0000747 } else {
748 fprintf(stderr, "Unable to get the locale encoding:\n");
749 PyErr_Print();
Victor Stinner7f84ab52010-06-11 00:36:33 +0000750 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000751
Victor Stinner94908bb2010-08-18 21:23:25 +0000752 fprintf(stderr, "Unable to get the filesystem encoding: fallback to utf-8\n");
Victor Stinner7f84ab52010-06-11 00:36:33 +0000753 Py_FileSystemDefaultEncoding = "utf-8";
754 Py_HasFileSystemDefaultEncoding = 1;
755 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000756#endif
757
758 /* the encoding is mbcs, utf-8 or ascii */
759 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
760 if (!codec) {
761 /* Such error can only occurs in critical situations: no more
762 * memory, import a module of the standard library failed,
763 * etc. */
764 Py_FatalError("Py_Initialize: unable to load the file system codec");
765 } else {
766 Py_DECREF(codec);
767 }
768}
769
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000770/* Import the site module (not into __main__ though) */
771
772static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000773initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 PyObject *m;
776 m = PyImport_ImportModule("site");
777 if (m == NULL) {
778 PyErr_Print();
779 Py_Finalize();
780 exit(1);
781 }
782 else {
783 Py_DECREF(m);
784 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000785}
786
Antoine Pitrou05608432009-01-09 18:53:14 +0000787static PyObject*
788create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 int fd, int write_mode, char* name,
790 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
793 const char* mode;
794 PyObject *line_buffering;
795 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 /* stdin is always opened in buffered mode, first because it shouldn't
798 make a difference in common use cases, second because TextIOWrapper
799 depends on the presence of a read1() method which only exists on
800 buffered streams.
801 */
802 if (Py_UnbufferedStdioFlag && write_mode)
803 buffering = 0;
804 else
805 buffering = -1;
806 if (write_mode)
807 mode = "wb";
808 else
809 mode = "rb";
810 buf = PyObject_CallMethod(io, "open", "isiOOOi",
811 fd, mode, buffering,
812 Py_None, Py_None, Py_None, 0);
813 if (buf == NULL)
814 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (buffering) {
817 raw = PyObject_GetAttrString(buf, "raw");
818 if (raw == NULL)
819 goto error;
820 }
821 else {
822 raw = buf;
823 Py_INCREF(raw);
824 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 text = PyUnicode_FromString(name);
827 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
828 goto error;
829 res = PyObject_CallMethod(raw, "isatty", "");
830 if (res == NULL)
831 goto error;
832 isatty = PyObject_IsTrue(res);
833 Py_DECREF(res);
834 if (isatty == -1)
835 goto error;
836 if (isatty || Py_UnbufferedStdioFlag)
837 line_buffering = Py_True;
838 else
839 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 Py_CLEAR(raw);
842 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
845 buf, encoding, errors,
846 "\n", line_buffering);
847 Py_CLEAR(buf);
848 if (stream == NULL)
849 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 if (write_mode)
852 mode = "w";
853 else
854 mode = "r";
855 text = PyUnicode_FromString(mode);
856 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
857 goto error;
858 Py_CLEAR(text);
859 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000860
861error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 Py_XDECREF(buf);
863 Py_XDECREF(stream);
864 Py_XDECREF(text);
865 Py_XDECREF(raw);
866 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000867}
868
Georg Brandl1a3284e2007-12-02 09:40:06 +0000869/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000870static int
871initstdio(void)
872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 PyObject *iomod = NULL, *wrapper;
874 PyObject *bimod = NULL;
875 PyObject *m;
876 PyObject *std = NULL;
877 int status = 0, fd;
878 PyObject * encoding_attr;
879 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 /* Hack to avoid a nasty recursion issue when Python is invoked
882 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
883 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
884 goto error;
885 }
886 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
889 goto error;
890 }
891 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 if (!(bimod = PyImport_ImportModule("builtins"))) {
894 goto error;
895 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 if (!(iomod = PyImport_ImportModule("io"))) {
898 goto error;
899 }
900 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
901 goto error;
902 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 /* Set builtins.open */
905 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
906 goto error;
907 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 encoding = Py_GETENV("PYTHONIOENCODING");
910 errors = NULL;
911 if (encoding) {
912 encoding = strdup(encoding);
913 errors = strchr(encoding, ':');
914 if (errors) {
915 *errors = '\0';
916 errors++;
917 }
918 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Set sys.stdin */
921 fd = fileno(stdin);
922 /* Under some conditions stdin, stdout and stderr may not be connected
923 * and fileno() may point to an invalid file descriptor. For example
924 * GUI apps don't have valid standard streams by default.
925 */
926 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000927#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 std = Py_None;
929 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000930#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000932#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 }
934 else {
935 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
936 if (std == NULL)
937 goto error;
938 } /* if (fd < 0) */
939 PySys_SetObject("__stdin__", std);
940 PySys_SetObject("stdin", std);
941 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 /* Set sys.stdout */
944 fd = fileno(stdout);
945 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000946#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 std = Py_None;
948 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000949#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000951#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 }
953 else {
954 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
955 if (std == NULL)
956 goto error;
957 } /* if (fd < 0) */
958 PySys_SetObject("__stdout__", std);
959 PySys_SetObject("stdout", std);
960 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000961
Guido van Rossum98297ee2007-11-06 21:34:58 +0000962#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* Set sys.stderr, replaces the preliminary stderr */
964 fd = fileno(stderr);
965 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000966#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 std = Py_None;
968 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000969#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000971#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 }
973 else {
974 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
975 if (std == NULL)
976 goto error;
977 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* Same as hack above, pre-import stderr's codec to avoid recursion
980 when import.c tries to write to stderr in verbose mode. */
981 encoding_attr = PyObject_GetAttrString(std, "encoding");
982 if (encoding_attr != NULL) {
983 const char * encoding;
984 encoding = _PyUnicode_AsString(encoding_attr);
985 if (encoding != NULL) {
986 _PyCodec_Lookup(encoding);
987 }
988 }
989 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PySys_SetObject("__stderr__", std);
992 PySys_SetObject("stderr", std);
993 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000994#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000997 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 status = -1;
999 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 if (encoding)
1002 free(encoding);
1003 Py_XDECREF(bimod);
1004 Py_XDECREF(iomod);
1005 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001006}
1007
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001008/* Parse input from a file and execute it */
1009
1010int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001011PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (filename == NULL)
1015 filename = "???";
1016 if (Py_FdIsInteractive(fp, filename)) {
1017 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1018 if (closeit)
1019 fclose(fp);
1020 return err;
1021 }
1022 else
1023 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001024}
1025
1026int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001027PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 PyObject *v;
1030 int ret;
1031 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 if (flags == NULL) {
1034 flags = &local_flags;
1035 local_flags.cf_flags = 0;
1036 }
1037 v = PySys_GetObject("ps1");
1038 if (v == NULL) {
1039 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1040 Py_XDECREF(v);
1041 }
1042 v = PySys_GetObject("ps2");
1043 if (v == NULL) {
1044 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1045 Py_XDECREF(v);
1046 }
1047 for (;;) {
1048 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1049 PRINT_TOTAL_REFS();
1050 if (ret == E_EOF)
1051 return 0;
1052 /*
1053 if (ret == E_NOMEM)
1054 return -1;
1055 */
1056 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001057}
1058
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001059/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001060static int PARSER_FLAGS(PyCompilerFlags *flags)
1061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 int parser_flags = 0;
1063 if (!flags)
1064 return 0;
1065 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1066 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1067 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1068 parser_flags |= PyPARSE_IGNORE_COOKIE;
1069 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1070 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1071 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001072}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001073
Thomas Wouters89f507f2006-12-13 04:49:30 +00001074#if 0
1075/* Keep an example of flags with future keyword support. */
1076#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1078 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1079 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1080 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001081#endif
1082
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001083int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001084PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 PyObject *m, *d, *v, *w, *oenc = NULL;
1087 mod_ty mod;
1088 PyArena *arena;
1089 char *ps1 = "", *ps2 = "", *enc = NULL;
1090 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (fp == stdin) {
1093 /* Fetch encoding from sys.stdin */
1094 v = PySys_GetObject("stdin");
1095 if (v == NULL || v == Py_None)
1096 return -1;
1097 oenc = PyObject_GetAttrString(v, "encoding");
1098 if (!oenc)
1099 return -1;
1100 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001101 if (enc == NULL)
1102 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 }
1104 v = PySys_GetObject("ps1");
1105 if (v != NULL) {
1106 v = PyObject_Str(v);
1107 if (v == NULL)
1108 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001109 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001111 if (ps1 == NULL) {
1112 PyErr_Clear();
1113 ps1 = "";
1114 }
1115 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 }
1117 w = PySys_GetObject("ps2");
1118 if (w != NULL) {
1119 w = PyObject_Str(w);
1120 if (w == NULL)
1121 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001122 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001124 if (ps2 == NULL) {
1125 PyErr_Clear();
1126 ps2 = "";
1127 }
1128 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 }
1130 arena = PyArena_New();
1131 if (arena == NULL) {
1132 Py_XDECREF(v);
1133 Py_XDECREF(w);
1134 Py_XDECREF(oenc);
1135 return -1;
1136 }
1137 mod = PyParser_ASTFromFile(fp, filename, enc,
1138 Py_single_input, ps1, ps2,
1139 flags, &errcode, arena);
1140 Py_XDECREF(v);
1141 Py_XDECREF(w);
1142 Py_XDECREF(oenc);
1143 if (mod == NULL) {
1144 PyArena_Free(arena);
1145 if (errcode == E_EOF) {
1146 PyErr_Clear();
1147 return E_EOF;
1148 }
1149 PyErr_Print();
1150 return -1;
1151 }
1152 m = PyImport_AddModule("__main__");
1153 if (m == NULL) {
1154 PyArena_Free(arena);
1155 return -1;
1156 }
1157 d = PyModule_GetDict(m);
1158 v = run_mod(mod, filename, d, d, flags, arena);
1159 PyArena_Free(arena);
1160 flush_io();
1161 if (v == NULL) {
1162 PyErr_Print();
1163 return -1;
1164 }
1165 Py_DECREF(v);
1166 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001167}
1168
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001169/* Check whether a file maybe a pyc file: Look at the extension,
1170 the file type, and, if we may close it, at the first few bytes. */
1171
1172static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001173maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1176 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 /* Only look into the file if we are allowed to close it, since
1179 it then should also be seekable. */
1180 if (closeit) {
1181 /* Read only two bytes of the magic. If the file was opened in
1182 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1183 be read as they are on disk. */
1184 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1185 unsigned char buf[2];
1186 /* Mess: In case of -x, the stream is NOT at its start now,
1187 and ungetc() was used to push back the first newline,
1188 which makes the current stream position formally undefined,
1189 and a x-platform nightmare.
1190 Unfortunately, we have no direct way to know whether -x
1191 was specified. So we use a terrible hack: if the current
1192 stream position is not 0, we assume -x was specified, and
1193 give up. Bug 132850 on SourceForge spells out the
1194 hopelessness of trying anything else (fseek and ftell
1195 don't work predictably x-platform for text-mode files).
1196 */
1197 int ispyc = 0;
1198 if (ftell(fp) == 0) {
1199 if (fread(buf, 1, 2, fp) == 2 &&
1200 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1201 ispyc = 1;
1202 rewind(fp);
1203 }
1204 return ispyc;
1205 }
1206 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001207}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001208
Guido van Rossum0df002c2000-08-27 19:21:52 +00001209int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001210PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 PyObject *m, *d, *v;
1214 const char *ext;
1215 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 m = PyImport_AddModule("__main__");
1218 if (m == NULL)
1219 return -1;
1220 d = PyModule_GetDict(m);
1221 if (PyDict_GetItemString(d, "__file__") == NULL) {
1222 PyObject *f;
Victor Stinner0fe25a42010-06-17 23:08:50 +00001223 f = PyUnicode_FromString(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 if (f == NULL)
1225 return -1;
1226 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1227 Py_DECREF(f);
1228 return -1;
1229 }
1230 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1231 return -1;
1232 set_file_name = 1;
1233 Py_DECREF(f);
1234 }
1235 len = strlen(filename);
1236 ext = filename + len - (len > 4 ? 4 : 0);
1237 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1238 /* Try to run a pyc file. First, re-open in binary */
1239 if (closeit)
1240 fclose(fp);
1241 if ((fp = fopen(filename, "rb")) == NULL) {
1242 fprintf(stderr, "python: Can't reopen .pyc file\n");
1243 ret = -1;
1244 goto done;
1245 }
1246 /* Turn on optimization if a .pyo file is given */
1247 if (strcmp(ext, ".pyo") == 0)
1248 Py_OptimizeFlag = 1;
1249 v = run_pyc_file(fp, filename, d, d, flags);
1250 } else {
1251 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1252 closeit, flags);
1253 }
1254 flush_io();
1255 if (v == NULL) {
1256 PyErr_Print();
1257 ret = -1;
1258 goto done;
1259 }
1260 Py_DECREF(v);
1261 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001262 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1264 PyErr_Clear();
1265 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001266}
1267
1268int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001269PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 PyObject *m, *d, *v;
1272 m = PyImport_AddModule("__main__");
1273 if (m == NULL)
1274 return -1;
1275 d = PyModule_GetDict(m);
1276 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1277 if (v == NULL) {
1278 PyErr_Print();
1279 return -1;
1280 }
1281 Py_DECREF(v);
1282 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001283}
1284
Barry Warsaw035574d1997-08-29 22:07:17 +00001285static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001286parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 long hold;
1290 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* old style errors */
1293 if (PyTuple_Check(err))
1294 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1295 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 if (! (v = PyObject_GetAttrString(err, "msg")))
1300 goto finally;
1301 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (!(v = PyObject_GetAttrString(err, "filename")))
1304 goto finally;
1305 if (v == Py_None)
1306 *filename = NULL;
1307 else if (! (*filename = _PyUnicode_AsString(v)))
1308 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 Py_DECREF(v);
1311 if (!(v = PyObject_GetAttrString(err, "lineno")))
1312 goto finally;
1313 hold = PyLong_AsLong(v);
1314 Py_DECREF(v);
1315 v = NULL;
1316 if (hold < 0 && PyErr_Occurred())
1317 goto finally;
1318 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (!(v = PyObject_GetAttrString(err, "offset")))
1321 goto finally;
1322 if (v == Py_None) {
1323 *offset = -1;
1324 Py_DECREF(v);
1325 v = NULL;
1326 } else {
1327 hold = PyLong_AsLong(v);
1328 Py_DECREF(v);
1329 v = NULL;
1330 if (hold < 0 && PyErr_Occurred())
1331 goto finally;
1332 *offset = (int)hold;
1333 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (!(v = PyObject_GetAttrString(err, "text")))
1336 goto finally;
1337 if (v == Py_None)
1338 *text = NULL;
1339 else if (!PyUnicode_Check(v) ||
1340 !(*text = _PyUnicode_AsString(v)))
1341 goto finally;
1342 Py_DECREF(v);
1343 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001344
1345finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 Py_XDECREF(v);
1347 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001348}
1349
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001350void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001351PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001354}
1355
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001356static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001357print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 char *nl;
1360 if (offset >= 0) {
1361 if (offset > 0 && offset == (int)strlen(text))
1362 offset--;
1363 for (;;) {
1364 nl = strchr(text, '\n');
1365 if (nl == NULL || nl-text >= offset)
1366 break;
1367 offset -= (int)(nl+1-text);
1368 text = nl+1;
1369 }
1370 while (*text == ' ' || *text == '\t') {
1371 text++;
1372 offset--;
1373 }
1374 }
1375 PyFile_WriteString(" ", f);
1376 PyFile_WriteString(text, f);
1377 if (*text == '\0' || text[strlen(text)-1] != '\n')
1378 PyFile_WriteString("\n", f);
1379 if (offset == -1)
1380 return;
1381 PyFile_WriteString(" ", f);
1382 offset--;
1383 while (offset > 0) {
1384 PyFile_WriteString(" ", f);
1385 offset--;
1386 }
1387 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001388}
1389
Guido van Rossum66e8e862001-03-23 17:54:43 +00001390static void
1391handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 PyObject *exception, *value, *tb;
1394 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 if (Py_InspectFlag)
1397 /* Don't exit if -i flag was given. This flag is set to 0
1398 * when entering interactive mode for inspecting. */
1399 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 PyErr_Fetch(&exception, &value, &tb);
1402 fflush(stdout);
1403 if (value == NULL || value == Py_None)
1404 goto done;
1405 if (PyExceptionInstance_Check(value)) {
1406 /* The error code should be in the `code' attribute. */
1407 PyObject *code = PyObject_GetAttrString(value, "code");
1408 if (code) {
1409 Py_DECREF(value);
1410 value = code;
1411 if (value == Py_None)
1412 goto done;
1413 }
1414 /* If we failed to dig out the 'code' attribute,
1415 just let the else clause below print the error. */
1416 }
1417 if (PyLong_Check(value))
1418 exitcode = (int)PyLong_AsLong(value);
1419 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001420 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001421 if (sys_stderr != NULL && sys_stderr != Py_None) {
1422 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1423 } else {
1424 PyObject_Print(value, stderr, Py_PRINT_RAW);
1425 fflush(stderr);
1426 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 PySys_WriteStderr("\n");
1428 exitcode = 1;
1429 }
Tim Peterscf615b52003-04-19 18:47:02 +00001430 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 /* Restore and clear the exception info, in order to properly decref
1432 * the exception, value, and traceback. If we just exit instead,
1433 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1434 * some finalizers from running.
1435 */
1436 PyErr_Restore(exception, value, tb);
1437 PyErr_Clear();
1438 Py_Exit(exitcode);
1439 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001440}
1441
1442void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001443PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1448 handle_system_exit();
1449 }
1450 PyErr_Fetch(&exception, &v, &tb);
1451 if (exception == NULL)
1452 return;
1453 PyErr_NormalizeException(&exception, &v, &tb);
1454 if (tb == NULL) {
1455 tb = Py_None;
1456 Py_INCREF(tb);
1457 }
1458 PyException_SetTraceback(v, tb);
1459 if (exception == NULL)
1460 return;
1461 /* Now we know v != NULL too */
1462 if (set_sys_last_vars) {
1463 PySys_SetObject("last_type", exception);
1464 PySys_SetObject("last_value", v);
1465 PySys_SetObject("last_traceback", tb);
1466 }
1467 hook = PySys_GetObject("excepthook");
1468 if (hook) {
1469 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1470 PyObject *result = PyEval_CallObject(hook, args);
1471 if (result == NULL) {
1472 PyObject *exception2, *v2, *tb2;
1473 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1474 handle_system_exit();
1475 }
1476 PyErr_Fetch(&exception2, &v2, &tb2);
1477 PyErr_NormalizeException(&exception2, &v2, &tb2);
1478 /* It should not be possible for exception2 or v2
1479 to be NULL. However PyErr_Display() can't
1480 tolerate NULLs, so just be safe. */
1481 if (exception2 == NULL) {
1482 exception2 = Py_None;
1483 Py_INCREF(exception2);
1484 }
1485 if (v2 == NULL) {
1486 v2 = Py_None;
1487 Py_INCREF(v2);
1488 }
1489 fflush(stdout);
1490 PySys_WriteStderr("Error in sys.excepthook:\n");
1491 PyErr_Display(exception2, v2, tb2);
1492 PySys_WriteStderr("\nOriginal exception was:\n");
1493 PyErr_Display(exception, v, tb);
1494 Py_DECREF(exception2);
1495 Py_DECREF(v2);
1496 Py_XDECREF(tb2);
1497 }
1498 Py_XDECREF(result);
1499 Py_XDECREF(args);
1500 } else {
1501 PySys_WriteStderr("sys.excepthook is missing\n");
1502 PyErr_Display(exception, v, tb);
1503 }
1504 Py_XDECREF(exception);
1505 Py_XDECREF(v);
1506 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001507}
1508
Benjamin Petersone6528212008-07-15 15:32:09 +00001509static void
1510print_exception(PyObject *f, PyObject *value)
1511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 int err = 0;
1513 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 if (!PyExceptionInstance_Check(value)) {
1516 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1517 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1518 PyFile_WriteString(" found\n", f);
1519 return;
1520 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 Py_INCREF(value);
1523 fflush(stdout);
1524 type = (PyObject *) Py_TYPE(value);
1525 tb = PyException_GetTraceback(value);
1526 if (tb && tb != Py_None)
1527 err = PyTraceBack_Print(tb, f);
1528 if (err == 0 &&
1529 PyObject_HasAttrString(value, "print_file_and_line"))
1530 {
1531 PyObject *message;
1532 const char *filename, *text;
1533 int lineno, offset;
1534 if (!parse_syntax_error(value, &message, &filename,
1535 &lineno, &offset, &text))
1536 PyErr_Clear();
1537 else {
1538 char buf[10];
1539 PyFile_WriteString(" File \"", f);
1540 if (filename == NULL)
1541 PyFile_WriteString("<string>", f);
1542 else
1543 PyFile_WriteString(filename, f);
1544 PyFile_WriteString("\", line ", f);
1545 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1546 PyFile_WriteString(buf, f);
1547 PyFile_WriteString("\n", f);
1548 if (text != NULL)
1549 print_error_text(f, offset, text);
1550 Py_DECREF(value);
1551 value = message;
1552 /* Can't be bothered to check all those
1553 PyFile_WriteString() calls */
1554 if (PyErr_Occurred())
1555 err = -1;
1556 }
1557 }
1558 if (err) {
1559 /* Don't do anything else */
1560 }
1561 else {
1562 PyObject* moduleName;
1563 char* className;
1564 assert(PyExceptionClass_Check(type));
1565 className = PyExceptionClass_Name(type);
1566 if (className != NULL) {
1567 char *dot = strrchr(className, '.');
1568 if (dot != NULL)
1569 className = dot+1;
1570 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 moduleName = PyObject_GetAttrString(type, "__module__");
1573 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1574 {
1575 Py_DECREF(moduleName);
1576 err = PyFile_WriteString("<unknown>", f);
1577 }
1578 else {
1579 char* modstr = _PyUnicode_AsString(moduleName);
1580 if (modstr && strcmp(modstr, "builtins"))
1581 {
1582 err = PyFile_WriteString(modstr, f);
1583 err += PyFile_WriteString(".", f);
1584 }
1585 Py_DECREF(moduleName);
1586 }
1587 if (err == 0) {
1588 if (className == NULL)
1589 err = PyFile_WriteString("<unknown>", f);
1590 else
1591 err = PyFile_WriteString(className, f);
1592 }
1593 }
1594 if (err == 0 && (value != Py_None)) {
1595 PyObject *s = PyObject_Str(value);
1596 /* only print colon if the str() of the
1597 object is not the empty string
1598 */
1599 if (s == NULL)
1600 err = -1;
1601 else if (!PyUnicode_Check(s) ||
1602 PyUnicode_GetSize(s) != 0)
1603 err = PyFile_WriteString(": ", f);
1604 if (err == 0)
1605 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1606 Py_XDECREF(s);
1607 }
1608 /* try to write a newline in any case */
1609 err += PyFile_WriteString("\n", f);
1610 Py_XDECREF(tb);
1611 Py_DECREF(value);
1612 /* If an error happened here, don't show it.
1613 XXX This is wrong, but too many callers rely on this behavior. */
1614 if (err != 0)
1615 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001616}
1617
1618static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 "\nThe above exception was the direct cause "
1620 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001621
1622static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 "\nDuring handling of the above exception, "
1624 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001625
1626static void
1627print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 int err = 0, res;
1630 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 if (seen != NULL) {
1633 /* Exception chaining */
1634 if (PySet_Add(seen, value) == -1)
1635 PyErr_Clear();
1636 else if (PyExceptionInstance_Check(value)) {
1637 cause = PyException_GetCause(value);
1638 context = PyException_GetContext(value);
1639 if (cause) {
1640 res = PySet_Contains(seen, cause);
1641 if (res == -1)
1642 PyErr_Clear();
1643 if (res == 0) {
1644 print_exception_recursive(
1645 f, cause, seen);
1646 err |= PyFile_WriteString(
1647 cause_message, f);
1648 }
1649 }
1650 else if (context) {
1651 res = PySet_Contains(seen, context);
1652 if (res == -1)
1653 PyErr_Clear();
1654 if (res == 0) {
1655 print_exception_recursive(
1656 f, context, seen);
1657 err |= PyFile_WriteString(
1658 context_message, f);
1659 }
1660 }
1661 Py_XDECREF(context);
1662 Py_XDECREF(cause);
1663 }
1664 }
1665 print_exception(f, value);
1666 if (err != 0)
1667 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001668}
1669
Thomas Wouters477c8d52006-05-27 19:21:47 +00001670void
1671PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001673 PyObject *seen;
1674 PyObject *f = PySys_GetObject("stderr");
1675 if (f == Py_None) {
1676 /* pass */
1677 }
1678 else if (f == NULL) {
1679 _PyObject_Dump(value);
1680 fprintf(stderr, "lost sys.stderr\n");
1681 }
1682 else {
1683 /* We choose to ignore seen being possibly NULL, and report
1684 at least the main exception (it could be a MemoryError).
1685 */
1686 seen = PySet_New(NULL);
1687 if (seen == NULL)
1688 PyErr_Clear();
1689 print_exception_recursive(f, value, seen);
1690 Py_XDECREF(seen);
1691 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001692}
1693
Guido van Rossum82598051997-03-05 00:20:32 +00001694PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001695PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 PyObject *ret = NULL;
1699 mod_ty mod;
1700 PyArena *arena = PyArena_New();
1701 if (arena == NULL)
1702 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1705 if (mod != NULL)
1706 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1707 PyArena_Free(arena);
1708 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001709}
1710
1711PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001712PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 PyObject *ret;
1716 mod_ty mod;
1717 PyArena *arena = PyArena_New();
1718 if (arena == NULL)
1719 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1722 flags, NULL, arena);
1723 if (closeit)
1724 fclose(fp);
1725 if (mod == NULL) {
1726 PyArena_Free(arena);
1727 return NULL;
1728 }
1729 ret = run_mod(mod, filename, globals, locals, flags, arena);
1730 PyArena_Free(arena);
1731 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001732}
1733
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001734static void
1735flush_io(void)
1736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyObject *f, *r;
1738 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 /* Save the current exception */
1741 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 f = PySys_GetObject("stderr");
1744 if (f != NULL) {
1745 r = PyObject_CallMethod(f, "flush", "");
1746 if (r)
1747 Py_DECREF(r);
1748 else
1749 PyErr_Clear();
1750 }
1751 f = PySys_GetObject("stdout");
1752 if (f != NULL) {
1753 r = PyObject_CallMethod(f, "flush", "");
1754 if (r)
1755 Py_DECREF(r);
1756 else
1757 PyErr_Clear();
1758 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001761}
1762
Guido van Rossum82598051997-03-05 00:20:32 +00001763static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 PyCodeObject *co;
1768 PyObject *v;
1769 co = PyAST_Compile(mod, filename, flags, arena);
1770 if (co == NULL)
1771 return NULL;
1772 v = PyEval_EvalCode(co, globals, locals);
1773 Py_DECREF(co);
1774 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001775}
1776
Guido van Rossum82598051997-03-05 00:20:32 +00001777static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001778run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 PyCodeObject *co;
1782 PyObject *v;
1783 long magic;
1784 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 magic = PyMarshal_ReadLongFromFile(fp);
1787 if (magic != PyImport_GetMagicNumber()) {
1788 PyErr_SetString(PyExc_RuntimeError,
1789 "Bad magic number in .pyc file");
1790 return NULL;
1791 }
1792 (void) PyMarshal_ReadLongFromFile(fp);
1793 v = PyMarshal_ReadLastObjectFromFile(fp);
1794 fclose(fp);
1795 if (v == NULL || !PyCode_Check(v)) {
1796 Py_XDECREF(v);
1797 PyErr_SetString(PyExc_RuntimeError,
1798 "Bad code object in .pyc file");
1799 return NULL;
1800 }
1801 co = (PyCodeObject *)v;
1802 v = PyEval_EvalCode(co, globals, locals);
1803 if (v && flags)
1804 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1805 Py_DECREF(co);
1806 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001807}
1808
Guido van Rossum82598051997-03-05 00:20:32 +00001809PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001810Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 PyCodeObject *co;
1814 mod_ty mod;
1815 PyArena *arena = PyArena_New();
1816 if (arena == NULL)
1817 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1820 if (mod == NULL) {
1821 PyArena_Free(arena);
1822 return NULL;
1823 }
1824 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1825 PyObject *result = PyAST_mod2obj(mod);
1826 PyArena_Free(arena);
1827 return result;
1828 }
1829 co = PyAST_Compile(mod, filename, flags, arena);
1830 PyArena_Free(arena);
1831 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001832}
1833
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001834struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001835Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 struct symtable *st;
1838 mod_ty mod;
1839 PyCompilerFlags flags;
1840 PyArena *arena = PyArena_New();
1841 if (arena == NULL)
1842 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 flags.cf_flags = 0;
1845 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1846 if (mod == NULL) {
1847 PyArena_Free(arena);
1848 return NULL;
1849 }
1850 st = PySymtable_Build(mod, filename, 0);
1851 PyArena_Free(arena);
1852 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001853}
1854
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001855/* Preferred access to parser is through AST. */
1856mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001857PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 mod_ty mod;
1861 PyCompilerFlags localflags;
1862 perrdetail err;
1863 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1866 &_PyParser_Grammar, start, &err,
1867 &iflags);
1868 if (flags == NULL) {
1869 localflags.cf_flags = 0;
1870 flags = &localflags;
1871 }
1872 if (n) {
1873 flags->cf_flags |= iflags & PyCF_MASK;
1874 mod = PyAST_FromNode(n, flags, filename, arena);
1875 PyNode_Free(n);
1876 return mod;
1877 }
1878 else {
1879 err_input(&err);
1880 return NULL;
1881 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001882}
1883
1884mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001885PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 int start, char *ps1,
1887 char *ps2, PyCompilerFlags *flags, int *errcode,
1888 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001889{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 mod_ty mod;
1891 PyCompilerFlags localflags;
1892 perrdetail err;
1893 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1896 &_PyParser_Grammar,
1897 start, ps1, ps2, &err, &iflags);
1898 if (flags == NULL) {
1899 localflags.cf_flags = 0;
1900 flags = &localflags;
1901 }
1902 if (n) {
1903 flags->cf_flags |= iflags & PyCF_MASK;
1904 mod = PyAST_FromNode(n, flags, filename, arena);
1905 PyNode_Free(n);
1906 return mod;
1907 }
1908 else {
1909 err_input(&err);
1910 if (errcode)
1911 *errcode = err.error;
1912 return NULL;
1913 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001914}
1915
Guido van Rossuma110aa61994-08-29 12:50:44 +00001916/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001917
Guido van Rossuma110aa61994-08-29 12:50:44 +00001918node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001919PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 perrdetail err;
1922 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1923 &_PyParser_Grammar,
1924 start, NULL, NULL, &err, flags);
1925 if (n == NULL)
1926 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001929}
1930
Guido van Rossuma110aa61994-08-29 12:50:44 +00001931/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001932
Guido van Rossuma110aa61994-08-29 12:50:44 +00001933node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001934PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 perrdetail err;
1937 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1938 start, &err, flags);
1939 if (n == NULL)
1940 err_input(&err);
1941 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001942}
1943
1944node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001945PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 perrdetail err;
1949 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1950 &_PyParser_Grammar, start, &err, flags);
1951 if (n == NULL)
1952 err_input(&err);
1953 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001954}
1955
1956node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001957PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001960}
1961
Guido van Rossum66ebd912003-04-17 16:02:26 +00001962/* May want to move a more generalized form of this to parsetok.c or
1963 even parser modules. */
1964
1965void
1966PyParser_SetError(perrdetail *err)
1967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001969}
1970
Guido van Rossuma110aa61994-08-29 12:50:44 +00001971/* Set the error appropriate to the given input error code (see errcode.h) */
1972
1973static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001974err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 PyObject *v, *w, *errtype, *errtext;
1977 PyObject *msg_obj = NULL;
1978 char *msg = NULL;
1979 errtype = PyExc_SyntaxError;
1980 switch (err->error) {
1981 case E_ERROR:
1982 return;
1983 case E_SYNTAX:
1984 errtype = PyExc_IndentationError;
1985 if (err->expected == INDENT)
1986 msg = "expected an indented block";
1987 else if (err->token == INDENT)
1988 msg = "unexpected indent";
1989 else if (err->token == DEDENT)
1990 msg = "unexpected unindent";
1991 else {
1992 errtype = PyExc_SyntaxError;
1993 msg = "invalid syntax";
1994 }
1995 break;
1996 case E_TOKEN:
1997 msg = "invalid token";
1998 break;
1999 case E_EOFS:
2000 msg = "EOF while scanning triple-quoted string literal";
2001 break;
2002 case E_EOLS:
2003 msg = "EOL while scanning string literal";
2004 break;
2005 case E_INTR:
2006 if (!PyErr_Occurred())
2007 PyErr_SetNone(PyExc_KeyboardInterrupt);
2008 goto cleanup;
2009 case E_NOMEM:
2010 PyErr_NoMemory();
2011 goto cleanup;
2012 case E_EOF:
2013 msg = "unexpected EOF while parsing";
2014 break;
2015 case E_TABSPACE:
2016 errtype = PyExc_TabError;
2017 msg = "inconsistent use of tabs and spaces in indentation";
2018 break;
2019 case E_OVERFLOW:
2020 msg = "expression too long";
2021 break;
2022 case E_DEDENT:
2023 errtype = PyExc_IndentationError;
2024 msg = "unindent does not match any outer indentation level";
2025 break;
2026 case E_TOODEEP:
2027 errtype = PyExc_IndentationError;
2028 msg = "too many levels of indentation";
2029 break;
2030 case E_DECODE: {
2031 PyObject *type, *value, *tb;
2032 PyErr_Fetch(&type, &value, &tb);
2033 msg = "unknown decode error";
2034 if (value != NULL)
2035 msg_obj = PyObject_Str(value);
2036 Py_XDECREF(type);
2037 Py_XDECREF(value);
2038 Py_XDECREF(tb);
2039 break;
2040 }
2041 case E_LINECONT:
2042 msg = "unexpected character after line continuation character";
2043 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 case E_IDENTIFIER:
2046 msg = "invalid character in identifier";
2047 break;
2048 default:
2049 fprintf(stderr, "error=%d\n", err->error);
2050 msg = "unknown parsing error";
2051 break;
2052 }
2053 /* err->text may not be UTF-8 in case of decoding errors.
2054 Explicitly convert to an object. */
2055 if (!err->text) {
2056 errtext = Py_None;
2057 Py_INCREF(Py_None);
2058 } else {
2059 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2060 "replace");
2061 }
2062 v = Py_BuildValue("(ziiN)", err->filename,
2063 err->lineno, err->offset, errtext);
2064 if (v != NULL) {
2065 if (msg_obj)
2066 w = Py_BuildValue("(OO)", msg_obj, v);
2067 else
2068 w = Py_BuildValue("(sO)", msg, v);
2069 } else
2070 w = NULL;
2071 Py_XDECREF(v);
2072 PyErr_SetObject(errtype, w);
2073 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002074cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 Py_XDECREF(msg_obj);
2076 if (err->text != NULL) {
2077 PyObject_FREE(err->text);
2078 err->text = NULL;
2079 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002080}
2081
2082/* Print fatal error message and abort */
2083
2084void
Tim Peters7c321a82002-07-09 02:57:01 +00002085Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 fprintf(stderr, "Fatal Python error: %s\n", msg);
2088 fflush(stderr); /* it helps in Windows debug build */
2089 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002090 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002092#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 {
2094 size_t len = strlen(msg);
2095 WCHAR* buffer;
2096 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 /* Convert the message to wchar_t. This uses a simple one-to-one
2099 conversion, assuming that the this error message actually uses ASCII
2100 only. If this ceases to be true, we will have to convert. */
2101 buffer = alloca( (len+1) * (sizeof *buffer));
2102 for( i=0; i<=len; ++i)
2103 buffer[i] = msg[i];
2104 OutputDebugStringW(L"Fatal Python error: ");
2105 OutputDebugStringW(buffer);
2106 OutputDebugStringW(L"\n");
2107 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002108#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002110#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002111#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002113}
2114
2115/* Clean up and exit */
2116
Guido van Rossuma110aa61994-08-29 12:50:44 +00002117#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002118#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002119#endif
2120
Collin Winter670e6922007-03-21 02:57:17 +00002121static void (*pyexitfunc)(void) = NULL;
2122/* For the atexit module. */
2123void _Py_PyAtExit(void (*func)(void))
2124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002126}
2127
2128static void
2129call_py_exitfuncs(void)
2130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 if (pyexitfunc == NULL)
2132 return;
Collin Winter670e6922007-03-21 02:57:17 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 (*pyexitfunc)();
2135 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002136}
2137
Antoine Pitrou011bd622009-10-20 21:52:47 +00002138/* Wait until threading._shutdown completes, provided
2139 the threading module was imported in the first place.
2140 The shutdown routine will wait until all non-daemon
2141 "threading" threads have completed. */
2142static void
2143wait_for_thread_shutdown(void)
2144{
2145#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 PyObject *result;
2147 PyThreadState *tstate = PyThreadState_GET();
2148 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2149 "threading");
2150 if (threading == NULL) {
2151 /* threading not imported */
2152 PyErr_Clear();
2153 return;
2154 }
2155 result = PyObject_CallMethod(threading, "_shutdown", "");
2156 if (result == NULL) {
2157 PyErr_WriteUnraisable(threading);
2158 }
2159 else {
2160 Py_DECREF(result);
2161 }
2162 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002163#endif
2164}
2165
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002166#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002167static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002168static int nexitfuncs = 0;
2169
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002170int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 if (nexitfuncs >= NEXITFUNCS)
2173 return -1;
2174 exitfuncs[nexitfuncs++] = func;
2175 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002176}
2177
Guido van Rossumcc283f51997-08-05 02:22:03 +00002178static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002179call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 while (nexitfuncs > 0)
2182 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 fflush(stdout);
2185 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002186}
2187
2188void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002189Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002194}
2195
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002196static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002197initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002198{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002199#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002201#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002202#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002204#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002205#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002207#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002209}
2210
Guido van Rossum7433b121997-02-14 19:45:36 +00002211
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002212/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2213 *
2214 * All of the code in this function must only use async-signal-safe functions,
2215 * listed at `man 7 signal` or
2216 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2217 */
2218void
2219_Py_RestoreSignals(void)
2220{
2221#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002223#endif
2224#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002226#endif
2227#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002229#endif
2230}
2231
2232
Guido van Rossum7433b121997-02-14 19:45:36 +00002233/*
2234 * The file descriptor fd is considered ``interactive'' if either
2235 * a) isatty(fd) is TRUE, or
2236 * b) the -i flag was given, and the filename associated with
2237 * the descriptor is NULL or "<stdin>" or "???".
2238 */
2239int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002240Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 if (isatty((int)fileno(fp)))
2243 return 1;
2244 if (!Py_InteractiveFlag)
2245 return 0;
2246 return (filename == NULL) ||
2247 (strcmp(filename, "<stdin>") == 0) ||
2248 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002249}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002250
2251
Tim Petersd08e3822003-04-17 15:24:21 +00002252#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002253#if defined(WIN32) && defined(_MSC_VER)
2254
2255/* Stack checking for Microsoft C */
2256
2257#include <malloc.h>
2258#include <excpt.h>
2259
Fred Drakee8de31c2000-08-31 05:38:39 +00002260/*
2261 * Return non-zero when we run out of memory on the stack; zero otherwise.
2262 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002263int
Fred Drake399739f2000-08-31 05:52:44 +00002264PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 __try {
2267 /* alloca throws a stack overflow exception if there's
2268 not enough space left on the stack */
2269 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2270 return 0;
2271 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2272 EXCEPTION_EXECUTE_HANDLER :
2273 EXCEPTION_CONTINUE_SEARCH) {
2274 int errcode = _resetstkoflw();
2275 if (errcode == 0)
2276 {
2277 Py_FatalError("Could not reset the stack!");
2278 }
2279 }
2280 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002281}
2282
2283#endif /* WIN32 && _MSC_VER */
2284
2285/* Alternate implementations can be added here... */
2286
2287#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002288
2289
2290/* Wrappers around sigaction() or signal(). */
2291
2292PyOS_sighandler_t
2293PyOS_getsig(int sig)
2294{
2295#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 struct sigaction context;
2297 if (sigaction(sig, NULL, &context) == -1)
2298 return SIG_ERR;
2299 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002300#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002302/* Special signal handling for the secure CRT in Visual Studio 2005 */
2303#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 switch (sig) {
2305 /* Only these signals are valid */
2306 case SIGINT:
2307 case SIGILL:
2308 case SIGFPE:
2309 case SIGSEGV:
2310 case SIGTERM:
2311 case SIGBREAK:
2312 case SIGABRT:
2313 break;
2314 /* Don't call signal() with other values or it will assert */
2315 default:
2316 return SIG_ERR;
2317 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002318#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 handler = signal(sig, SIG_IGN);
2320 if (handler != SIG_ERR)
2321 signal(sig, handler);
2322 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002323#endif
2324}
2325
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002326/*
2327 * All of the code in this function must only use async-signal-safe functions,
2328 * listed at `man 7 signal` or
2329 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2330 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002331PyOS_sighandler_t
2332PyOS_setsig(int sig, PyOS_sighandler_t handler)
2333{
2334#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 /* Some code in Modules/signalmodule.c depends on sigaction() being
2336 * used here if HAVE_SIGACTION is defined. Fix that if this code
2337 * changes to invalidate that assumption.
2338 */
2339 struct sigaction context, ocontext;
2340 context.sa_handler = handler;
2341 sigemptyset(&context.sa_mask);
2342 context.sa_flags = 0;
2343 if (sigaction(sig, &context, &ocontext) == -1)
2344 return SIG_ERR;
2345 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002346#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 PyOS_sighandler_t oldhandler;
2348 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002349#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002351#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002353#endif
2354}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002355
2356/* Deprecated C API functions still provided for binary compatiblity */
2357
2358#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002359PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002360PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002363}
2364
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002365#undef PyParser_SimpleParseString
2366PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002367PyParser_SimpleParseString(const char *str, int start)
2368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002370}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002371
2372#undef PyRun_AnyFile
2373PyAPI_FUNC(int)
2374PyRun_AnyFile(FILE *fp, const char *name)
2375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002377}
2378
2379#undef PyRun_AnyFileEx
2380PyAPI_FUNC(int)
2381PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002384}
2385
2386#undef PyRun_AnyFileFlags
2387PyAPI_FUNC(int)
2388PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002391}
2392
2393#undef PyRun_File
2394PyAPI_FUNC(PyObject *)
2395PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002398}
2399
2400#undef PyRun_FileEx
2401PyAPI_FUNC(PyObject *)
2402PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002405}
2406
2407#undef PyRun_FileFlags
2408PyAPI_FUNC(PyObject *)
2409PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002413}
2414
2415#undef PyRun_SimpleFile
2416PyAPI_FUNC(int)
2417PyRun_SimpleFile(FILE *f, const char *p)
2418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002420}
2421
2422#undef PyRun_SimpleFileEx
2423PyAPI_FUNC(int)
2424PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002427}
2428
2429
2430#undef PyRun_String
2431PyAPI_FUNC(PyObject *)
2432PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002435}
2436
2437#undef PyRun_SimpleString
2438PyAPI_FUNC(int)
2439PyRun_SimpleString(const char *s)
2440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002442}
2443
2444#undef Py_CompileString
2445PyAPI_FUNC(PyObject *)
2446Py_CompileString(const char *str, const char *p, int s)
2447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002449}
2450
2451#undef PyRun_InteractiveOne
2452PyAPI_FUNC(int)
2453PyRun_InteractiveOne(FILE *f, const char *p)
2454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002456}
2457
2458#undef PyRun_InteractiveLoop
2459PyAPI_FUNC(int)
2460PyRun_InteractiveLoop(FILE *f, const char *p)
2461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002463}
2464
2465#ifdef __cplusplus
2466}
2467#endif