blob: d3981961ee5a67aa55271cb9a223ed87e1a4da2b [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Antoine Pitrou011bd622009-10-20 21:52:47 +000021#include "abstract.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000022
Thomas Wouters0e3f5912006-08-11 14:57:12 +000023#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000024#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000026
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000027#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000028#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000029#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000030
Martin v. Löwis73d538b2003-03-05 15:13:47 +000031#ifdef HAVE_LANGINFO_H
32#include <locale.h>
33#include <langinfo.h>
34#endif
35
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000036#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000037#undef BYTE
38#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000039#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000040#endif
41
Neal Norwitz4281cef2006-03-04 19:58:13 +000042#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000044#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000045#define PRINT_TOTAL_REFS() fprintf(stderr, \
46 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
47 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000048#endif
49
50#ifdef __cplusplus
51extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000052#endif
53
Martin v. Löwis790465f2008-04-05 20:41:37 +000054extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000055
Guido van Rossum82598051997-03-05 00:20:32 +000056extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000057
Guido van Rossumb73cc041993-11-01 16:28:59 +000058/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000059static void initmain(void);
Victor Stinnerb744ba12010-05-15 12:27:16 +000060static void initfsencoding(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000061static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000062static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000063static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000066static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000068static void err_input(perrdetail *);
69static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000070static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000071static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000072static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000073extern void _PyUnicode_Init(void);
74extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000075extern int _PyLong_Init(void);
76extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000077
Mark Hammond8d98d2c2003-04-19 15:41:53 +000078#ifdef WITH_THREAD
79extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
80extern void _PyGILState_Fini(void);
81#endif /* WITH_THREAD */
82
Guido van Rossum82598051997-03-05 00:20:32 +000083int Py_DebugFlag; /* Needed by parser.c */
84int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000085int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000086int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000087int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000088int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000089int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000090int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000091int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000092int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000094int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000095
Christian Heimes33fe8092008-04-13 13:53:33 +000096/* PyModule_GetWarningsModule is no longer necessary as of 2.6
97since _warnings is builtin. This API should not be used. */
98PyObject *
99PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000102}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000103
Guido van Rossum25ce5661997-08-02 03:10:38 +0000104static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000105
Thomas Wouters7e474022000-07-16 12:04:32 +0000106/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000107
108int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000109Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000112}
113
Guido van Rossum25ce5661997-08-02 03:10:38 +0000114/* Global initializations. Can be undone by Py_Finalize(). Don't
115 call this twice without an intervening Py_Finalize() call. When
116 initializations fail, a fatal error is issued and the function does
117 not return. On return, the first thread and interpreter state have
118 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000119
Guido van Rossum25ce5661997-08-02 03:10:38 +0000120 Locking: you must hold the interpreter lock while calling this.
121 (If the lock has not yet been initialized, that's equivalent to
122 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000123
Guido van Rossum25ce5661997-08-02 03:10:38 +0000124*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000125
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000126static int
127add_flag(int flag, const char *envs)
128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 int env = atoi(envs);
130 if (flag < env)
131 flag = env;
132 if (flag < 1)
133 flag = 1;
134 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000135}
136
Christian Heimes5833a2f2008-10-30 21:40:04 +0000137#if defined(HAVE_LANGINFO_H) && defined(CODESET)
138static char*
139get_codeset(void)
140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 char* codeset;
142 PyObject *codec, *name;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 codeset = nl_langinfo(CODESET);
145 if (!codeset || codeset[0] == '\0')
146 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 codec = _PyCodec_Lookup(codeset);
149 if (!codec)
150 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 name = PyObject_GetAttrString(codec, "name");
153 Py_CLEAR(codec);
154 if (!name)
155 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 codeset = strdup(_PyUnicode_AsString(name));
158 Py_DECREF(name);
159 return codeset;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000160
161error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 Py_XDECREF(codec);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000164}
165#endif
166
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000168Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 PyInterpreterState *interp;
171 PyThreadState *tstate;
172 PyObject *bimod, *sysmod, *pstderr;
173 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (initialized)
177 return;
178 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000179
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000180#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 /* Set up the LC_CTYPE locale, so we can obtain
182 the locale's charset without having to switch
183 locales. */
184 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000185#endif
186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
188 Py_DebugFlag = add_flag(Py_DebugFlag, p);
189 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
190 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
191 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
192 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
193 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
194 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 interp = PyInterpreterState_New();
197 if (interp == NULL)
198 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 tstate = PyThreadState_New(interp);
201 if (tstate == NULL)
202 Py_FatalError("Py_Initialize: can't make first thread");
203 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if (!_PyFrame_Init())
208 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (!_PyLong_Init())
211 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (!PyByteArray_Init())
214 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 interp->modules = PyDict_New();
219 if (interp->modules == NULL)
220 Py_FatalError("Py_Initialize: can't make modules dictionary");
221 interp->modules_reloading = PyDict_New();
222 if (interp->modules_reloading == NULL)
223 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 /* Init Unicode implementation; relies on the codec registry */
226 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 bimod = _PyBuiltin_Init();
229 if (bimod == NULL)
230 Py_FatalError("Py_Initialize: can't initialize builtins modules");
231 _PyImport_FixupExtension(bimod, "builtins", "builtins");
232 interp->builtins = PyModule_GetDict(bimod);
233 if (interp->builtins == NULL)
234 Py_FatalError("Py_Initialize: can't initialize builtins dict");
235 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 /* initialize builtin exceptions */
238 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 sysmod = _PySys_Init();
241 if (sysmod == NULL)
242 Py_FatalError("Py_Initialize: can't initialize sys");
243 interp->sysdict = PyModule_GetDict(sysmod);
244 if (interp->sysdict == NULL)
245 Py_FatalError("Py_Initialize: can't initialize sys dict");
246 Py_INCREF(interp->sysdict);
247 _PyImport_FixupExtension(sysmod, "sys", "sys");
248 PySys_SetPath(Py_GetPath());
249 PyDict_SetItemString(interp->sysdict, "modules",
250 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 /* Set up a preliminary stderr printer until we have enough
253 infrastructure for the io module in place. */
254 pstderr = PyFile_NewStdPrinter(fileno(stderr));
255 if (pstderr == NULL)
256 Py_FatalError("Py_Initialize: can't set preliminary stderr");
257 PySys_SetObject("stderr", pstderr);
258 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000263
Victor Stinnerb744ba12010-05-15 12:27:16 +0000264 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 if (install_sigs)
267 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 /* Initialize warnings. */
270 _PyWarnings_Init();
271 if (PySys_HasWarnOptions()) {
272 PyObject *warnings_module = PyImport_ImportModule("warnings");
273 if (!warnings_module)
274 PyErr_Clear();
275 Py_XDECREF(warnings_module);
276 }
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 initmain(); /* Module __main__ */
279 if (initstdio() < 0)
280 Py_FatalError(
281 "Py_Initialize: can't initialize sys standard streams");
282
283 /* auto-thread-state API, if available */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000284#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 _PyGILState_Init(interp, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000286#endif /* WITH_THREAD */
Victor Stinner52f6dd72010-03-12 14:45:56 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 if (!Py_NoSiteFlag)
289 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000290}
291
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000292void
293Py_Initialize(void)
294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000296}
297
298
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000299#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000300extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000301#endif
302
Guido van Rossume8432ac2007-07-09 15:04:50 +0000303/* Flush stdout and stderr */
304
Neal Norwitz2bad9702007-08-27 06:19:22 +0000305static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000306flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 PyObject *fout = PySys_GetObject("stdout");
309 PyObject *ferr = PySys_GetObject("stderr");
310 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (fout != NULL && fout != Py_None) {
313 tmp = PyObject_CallMethod(fout, "flush", "");
314 if (tmp == NULL)
315 PyErr_Clear();
316 else
317 Py_DECREF(tmp);
318 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000319
Victor Stinner9467b212010-05-14 00:59:09 +0000320 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 tmp = PyObject_CallMethod(ferr, "flush", "");
322 if (tmp == NULL)
323 PyErr_Clear();
324 else
325 Py_DECREF(tmp);
326 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000327}
328
Guido van Rossum25ce5661997-08-02 03:10:38 +0000329/* Undo the effect of Py_Initialize().
330
331 Beware: if multiple interpreter and/or thread states exist, these
332 are not wiped out; only the current thread and interpreter state
333 are deleted. But since everything else is deleted, those other
334 interpreter and thread states should no longer be used.
335
336 (XXX We should do better, e.g. wipe out all interpreters and
337 threads.)
338
339 Locking: as above.
340
341*/
342
343void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000344Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 PyInterpreterState *interp;
347 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 if (!initialized)
350 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 /* The interpreter is still entirely intact at this point, and the
355 * exit funcs may be relying on that. In particular, if some thread
356 * or exit func is still waiting to do an import, the import machinery
357 * expects Py_IsInitialized() to return true. So don't say the
358 * interpreter is uninitialized until after the exit funcs have run.
359 * Note that Threading.py uses an exit func to do a join on all the
360 * threads created thru it, so this also protects pending imports in
361 * the threads created via Threading.
362 */
363 call_py_exitfuncs();
364 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 /* Flush stdout+stderr */
367 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 /* Get current thread state and interpreter pointer */
370 tstate = PyThreadState_GET();
371 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 /* Disable signal handling */
374 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 /* Clear type lookup cache */
377 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 /* Collect garbage. This may call finalizers; it's nice to call these
380 * before all modules are destroyed.
381 * XXX If a __del__ or weakref callback is triggered here, and tries to
382 * XXX import a module, bad things can happen, because Python no
383 * XXX longer believes it's initialized.
384 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
385 * XXX is easy to provoke that way. I've also seen, e.g.,
386 * XXX Exception exceptions.ImportError: 'No module named sha'
387 * XXX in <function callback at 0x008F5718> ignored
388 * XXX but I'm unclear on exactly how that one happens. In any case,
389 * XXX I haven't seen a real-life report of either of these.
390 */
391 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000392#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* With COUNT_ALLOCS, it helps to run GC multiple times:
394 each collection might release some types from the type
395 list, so they become garbage. */
396 while (PyGC_Collect() > 0)
397 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000398#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 /* Destroy all modules */
401 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 /* Flush stdout+stderr (again, in case more was printed) */
404 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 /* Collect final garbage. This disposes of cycles created by
407 * new-style class definitions, for example.
408 * XXX This is disabled because it caused too many problems. If
409 * XXX a __del__ or weakref callback triggers here, Python code has
410 * XXX a hard time running, because even the sys module has been
411 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
412 * XXX One symptom is a sequence of information-free messages
413 * XXX coming from threads (if a __del__ or callback is invoked,
414 * XXX other threads can execute too, and any exception they encounter
415 * XXX triggers a comedy of errors as subsystem after subsystem
416 * XXX fails to find what it *expects* to find in sys to help report
417 * XXX the exception and consequent unexpected failures). I've also
418 * XXX seen segfaults then, after adding print statements to the
419 * XXX Python code getting called.
420 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000421#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000423#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
426 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000429#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000431#endif
432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000434
Tim Peters9cf25ce2003-04-17 15:21:01 +0000435#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 /* Display all objects still alive -- this can invoke arbitrary
437 * __repr__ overrides, so requires a mostly-intact interpreter.
438 * Alas, a lot of stuff may still be alive now that will be cleaned
439 * up later.
440 */
441 if (Py_GETENV("PYTHONDUMPREFS"))
442 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000443#endif /* Py_TRACE_REFS */
444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 /* Clear interpreter state */
446 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 /* Now we decref the exception classes. After this point nothing
449 can raise an exception. That's okay, because each Fini() method
450 below has been checked to make sure no exceptions are ever
451 raised.
452 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000457#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000459#endif /* WITH_THREAD */
460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 /* Delete current thread */
462 PyThreadState_Swap(NULL);
463 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* Sundry finalizers */
466 PyMethod_Fini();
467 PyFrame_Fini();
468 PyCFunction_Fini();
469 PyTuple_Fini();
470 PyList_Fini();
471 PySet_Fini();
472 PyBytes_Fini();
473 PyByteArray_Fini();
474 PyLong_Fini();
475 PyFloat_Fini();
476 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 /* Cleanup Unicode implementation */
479 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000482 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 free((char*)Py_FileSystemDefaultEncoding);
484 Py_FileSystemDefaultEncoding = NULL;
485 }
Christian Heimesc8967002007-11-30 10:18:26 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 /* XXX Still allocated:
488 - various static ad-hoc pointers to interned strings
489 - int and float free list blocks
490 - whatever various modules and libraries allocate
491 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000494
Tim Peters269b2a62003-04-17 19:52:29 +0000495#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 /* Display addresses (& refcnts) of all objects still alive.
497 * An address can be used to find the repr of the object, printed
498 * above by _Py_PrintReferences.
499 */
500 if (Py_GETENV("PYTHONDUMPREFS"))
501 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000502#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000503#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (Py_GETENV("PYTHONMALLOCSTATS"))
505 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000506#endif
507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000509}
510
511/* Create and initialize a new interpreter and thread, and return the
512 new thread. This requires that Py_Initialize() has been called
513 first.
514
515 Unsuccessful initialization yields a NULL pointer. Note that *no*
516 exception information is available even in this case -- the
517 exception information is held in the thread, and there is no
518 thread.
519
520 Locking: as above.
521
522*/
523
524PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000525Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 PyInterpreterState *interp;
528 PyThreadState *tstate, *save_tstate;
529 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (!initialized)
532 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 interp = PyInterpreterState_New();
535 if (interp == NULL)
536 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 tstate = PyThreadState_New(interp);
539 if (tstate == NULL) {
540 PyInterpreterState_Delete(interp);
541 return NULL;
542 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 interp->modules = PyDict_New();
549 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 bimod = _PyImport_FindExtension("builtins", "builtins");
552 if (bimod != NULL) {
553 interp->builtins = PyModule_GetDict(bimod);
554 if (interp->builtins == NULL)
555 goto handle_error;
556 Py_INCREF(interp->builtins);
557 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 /* initialize builtin exceptions */
560 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 sysmod = _PyImport_FindExtension("sys", "sys");
563 if (bimod != NULL && sysmod != NULL) {
564 PyObject *pstderr;
565 interp->sysdict = PyModule_GetDict(sysmod);
566 if (interp->sysdict == NULL)
567 goto handle_error;
568 Py_INCREF(interp->sysdict);
569 PySys_SetPath(Py_GetPath());
570 PyDict_SetItemString(interp->sysdict, "modules",
571 interp->modules);
572 /* Set up a preliminary stderr printer until we have enough
573 infrastructure for the io module in place. */
574 pstderr = PyFile_NewStdPrinter(fileno(stderr));
575 if (pstderr == NULL)
576 Py_FatalError("Py_Initialize: can't set preliminary stderr");
577 PySys_SetObject("stderr", pstderr);
578 PySys_SetObject("__stderr__", pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 _PyImportHooks_Init();
581 if (initstdio() < 0)
582 Py_FatalError(
583 "Py_Initialize: can't initialize sys standard streams");
584 initmain();
585 if (!Py_NoSiteFlag)
586 initsite();
587 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (!PyErr_Occurred())
590 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591
Thomas Wouters89f507f2006-12-13 04:49:30 +0000592handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 PyErr_Print();
596 PyThreadState_Clear(tstate);
597 PyThreadState_Swap(save_tstate);
598 PyThreadState_Delete(tstate);
599 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000602}
603
604/* Delete an interpreter and its last thread. This requires that the
605 given thread state is current, that the thread has no remaining
606 frames, and that it is its interpreter's only remaining thread.
607 It is a fatal error to violate these constraints.
608
609 (Py_Finalize() doesn't have these constraints -- it zaps
610 everything, regardless.)
611
612 Locking: as above.
613
614*/
615
616void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000617Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 if (tstate != PyThreadState_GET())
622 Py_FatalError("Py_EndInterpreter: thread is not current");
623 if (tstate->frame != NULL)
624 Py_FatalError("Py_EndInterpreter: thread still has a frame");
625 if (tstate != interp->tstate_head || tstate->next != NULL)
626 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 PyImport_Cleanup();
629 PyInterpreterState_Clear(interp);
630 PyThreadState_Swap(NULL);
631 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000632}
633
Martin v. Löwis790465f2008-04-05 20:41:37 +0000634static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000635
636void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000637Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000638{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 if (pn && *pn)
640 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000641}
642
Martin v. Löwis790465f2008-04-05 20:41:37 +0000643wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000644Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000647}
648
Martin v. Löwis790465f2008-04-05 20:41:37 +0000649static wchar_t *default_home = NULL;
650static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000651
652void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000653Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000656}
657
Martin v. Löwis790465f2008-04-05 20:41:37 +0000658wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000659Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 wchar_t *home = default_home;
662 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
663 char* chome = Py_GETENV("PYTHONHOME");
664 if (chome) {
665 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
666 if (r != (size_t)-1 && r <= PATH_MAX)
667 home = env_home;
668 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 }
671 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000672}
673
Guido van Rossum6135a871995-01-09 17:53:26 +0000674/* Create __main__ module */
675
676static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000677initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyObject *m, *d;
680 m = PyImport_AddModule("__main__");
681 if (m == NULL)
682 Py_FatalError("can't create __main__ module");
683 d = PyModule_GetDict(m);
684 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
685 PyObject *bimod = PyImport_ImportModule("builtins");
686 if (bimod == NULL ||
687 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
688 Py_FatalError("can't add __builtins__ to __main__");
689 Py_DECREF(bimod);
690 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000691}
692
Victor Stinnerb744ba12010-05-15 12:27:16 +0000693static void
694initfsencoding(void)
695{
696 PyObject *codec;
697#if defined(HAVE_LANGINFO_H) && defined(CODESET)
698 char *codeset;
699
700 /* On Unix, set the file system encoding according to the
701 user's preference, if the CODESET names a well-known
702 Python codec, and Py_FileSystemDefaultEncoding isn't
703 initialized by other means. Also set the encoding of
704 stdin and stdout if these are terminals. */
705 codeset = get_codeset();
706 if (codeset != NULL) {
707 Py_FileSystemDefaultEncoding = codeset;
708 Py_HasFileSystemDefaultEncoding = 0;
709 return;
710 }
711
712 PyErr_Clear();
713 fprintf(stderr,
714 "Unable to get the locale encoding: "
715 "fallback to utf-8\n");
716 Py_FileSystemDefaultEncoding = "utf-8";
717 Py_HasFileSystemDefaultEncoding = 1;
718#endif
719
720 /* the encoding is mbcs, utf-8 or ascii */
721 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
722 if (!codec) {
723 /* Such error can only occurs in critical situations: no more
724 * memory, import a module of the standard library failed,
725 * etc. */
726 Py_FatalError("Py_Initialize: unable to load the file system codec");
727 } else {
728 Py_DECREF(codec);
729 }
730}
731
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000732/* Import the site module (not into __main__ though) */
733
734static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000735initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 PyObject *m;
738 m = PyImport_ImportModule("site");
739 if (m == NULL) {
740 PyErr_Print();
741 Py_Finalize();
742 exit(1);
743 }
744 else {
745 Py_DECREF(m);
746 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000747}
748
Antoine Pitrou05608432009-01-09 18:53:14 +0000749static PyObject*
750create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 int fd, int write_mode, char* name,
752 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
755 const char* mode;
756 PyObject *line_buffering;
757 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 /* stdin is always opened in buffered mode, first because it shouldn't
760 make a difference in common use cases, second because TextIOWrapper
761 depends on the presence of a read1() method which only exists on
762 buffered streams.
763 */
764 if (Py_UnbufferedStdioFlag && write_mode)
765 buffering = 0;
766 else
767 buffering = -1;
768 if (write_mode)
769 mode = "wb";
770 else
771 mode = "rb";
772 buf = PyObject_CallMethod(io, "open", "isiOOOi",
773 fd, mode, buffering,
774 Py_None, Py_None, Py_None, 0);
775 if (buf == NULL)
776 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (buffering) {
779 raw = PyObject_GetAttrString(buf, "raw");
780 if (raw == NULL)
781 goto error;
782 }
783 else {
784 raw = buf;
785 Py_INCREF(raw);
786 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 text = PyUnicode_FromString(name);
789 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
790 goto error;
791 res = PyObject_CallMethod(raw, "isatty", "");
792 if (res == NULL)
793 goto error;
794 isatty = PyObject_IsTrue(res);
795 Py_DECREF(res);
796 if (isatty == -1)
797 goto error;
798 if (isatty || Py_UnbufferedStdioFlag)
799 line_buffering = Py_True;
800 else
801 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 Py_CLEAR(raw);
804 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
807 buf, encoding, errors,
808 "\n", line_buffering);
809 Py_CLEAR(buf);
810 if (stream == NULL)
811 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (write_mode)
814 mode = "w";
815 else
816 mode = "r";
817 text = PyUnicode_FromString(mode);
818 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
819 goto error;
820 Py_CLEAR(text);
821 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000822
823error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 Py_XDECREF(buf);
825 Py_XDECREF(stream);
826 Py_XDECREF(text);
827 Py_XDECREF(raw);
828 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000829}
830
Georg Brandl1a3284e2007-12-02 09:40:06 +0000831/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000832static int
833initstdio(void)
834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *iomod = NULL, *wrapper;
836 PyObject *bimod = NULL;
837 PyObject *m;
838 PyObject *std = NULL;
839 int status = 0, fd;
840 PyObject * encoding_attr;
841 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 /* Hack to avoid a nasty recursion issue when Python is invoked
844 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
845 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
846 goto error;
847 }
848 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
851 goto error;
852 }
853 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (!(bimod = PyImport_ImportModule("builtins"))) {
856 goto error;
857 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 if (!(iomod = PyImport_ImportModule("io"))) {
860 goto error;
861 }
862 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
863 goto error;
864 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 /* Set builtins.open */
867 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
868 goto error;
869 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 encoding = Py_GETENV("PYTHONIOENCODING");
872 errors = NULL;
873 if (encoding) {
874 encoding = strdup(encoding);
875 errors = strchr(encoding, ':');
876 if (errors) {
877 *errors = '\0';
878 errors++;
879 }
880 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* Set sys.stdin */
883 fd = fileno(stdin);
884 /* Under some conditions stdin, stdout and stderr may not be connected
885 * and fileno() may point to an invalid file descriptor. For example
886 * GUI apps don't have valid standard streams by default.
887 */
888 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000889#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 std = Py_None;
891 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000892#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000894#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 }
896 else {
897 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
898 if (std == NULL)
899 goto error;
900 } /* if (fd < 0) */
901 PySys_SetObject("__stdin__", std);
902 PySys_SetObject("stdin", std);
903 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 /* Set sys.stdout */
906 fd = fileno(stdout);
907 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000908#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 std = Py_None;
910 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000911#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000913#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 }
915 else {
916 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
917 if (std == NULL)
918 goto error;
919 } /* if (fd < 0) */
920 PySys_SetObject("__stdout__", std);
921 PySys_SetObject("stdout", std);
922 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000923
Guido van Rossum98297ee2007-11-06 21:34:58 +0000924#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 /* Set sys.stderr, replaces the preliminary stderr */
926 fd = fileno(stderr);
927 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000928#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 std = Py_None;
930 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000931#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000933#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 }
935 else {
936 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
937 if (std == NULL)
938 goto error;
939 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Same as hack above, pre-import stderr's codec to avoid recursion
942 when import.c tries to write to stderr in verbose mode. */
943 encoding_attr = PyObject_GetAttrString(std, "encoding");
944 if (encoding_attr != NULL) {
945 const char * encoding;
946 encoding = _PyUnicode_AsString(encoding_attr);
947 if (encoding != NULL) {
948 _PyCodec_Lookup(encoding);
949 }
950 }
951 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 PySys_SetObject("__stderr__", std);
954 PySys_SetObject("stderr", std);
955 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000956#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000959 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 status = -1;
961 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 if (encoding)
964 free(encoding);
965 Py_XDECREF(bimod);
966 Py_XDECREF(iomod);
967 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000968}
969
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000970/* Parse input from a file and execute it */
971
972int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000973PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (filename == NULL)
977 filename = "???";
978 if (Py_FdIsInteractive(fp, filename)) {
979 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
980 if (closeit)
981 fclose(fp);
982 return err;
983 }
984 else
985 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000986}
987
988int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000989PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 PyObject *v;
992 int ret;
993 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 if (flags == NULL) {
996 flags = &local_flags;
997 local_flags.cf_flags = 0;
998 }
999 v = PySys_GetObject("ps1");
1000 if (v == NULL) {
1001 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1002 Py_XDECREF(v);
1003 }
1004 v = PySys_GetObject("ps2");
1005 if (v == NULL) {
1006 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1007 Py_XDECREF(v);
1008 }
1009 for (;;) {
1010 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1011 PRINT_TOTAL_REFS();
1012 if (ret == E_EOF)
1013 return 0;
1014 /*
1015 if (ret == E_NOMEM)
1016 return -1;
1017 */
1018 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001019}
1020
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001021/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001022static int PARSER_FLAGS(PyCompilerFlags *flags)
1023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 int parser_flags = 0;
1025 if (!flags)
1026 return 0;
1027 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1028 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1029 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1030 parser_flags |= PyPARSE_IGNORE_COOKIE;
1031 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1032 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1033 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001034}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001035
Thomas Wouters89f507f2006-12-13 04:49:30 +00001036#if 0
1037/* Keep an example of flags with future keyword support. */
1038#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1040 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1041 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1042 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001043#endif
1044
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001045int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001046PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 PyObject *m, *d, *v, *w, *oenc = NULL;
1049 mod_ty mod;
1050 PyArena *arena;
1051 char *ps1 = "", *ps2 = "", *enc = NULL;
1052 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 if (fp == stdin) {
1055 /* Fetch encoding from sys.stdin */
1056 v = PySys_GetObject("stdin");
1057 if (v == NULL || v == Py_None)
1058 return -1;
1059 oenc = PyObject_GetAttrString(v, "encoding");
1060 if (!oenc)
1061 return -1;
1062 enc = _PyUnicode_AsString(oenc);
1063 }
1064 v = PySys_GetObject("ps1");
1065 if (v != NULL) {
1066 v = PyObject_Str(v);
1067 if (v == NULL)
1068 PyErr_Clear();
1069 else if (PyUnicode_Check(v))
1070 ps1 = _PyUnicode_AsString(v);
1071 }
1072 w = PySys_GetObject("ps2");
1073 if (w != NULL) {
1074 w = PyObject_Str(w);
1075 if (w == NULL)
1076 PyErr_Clear();
1077 else if (PyUnicode_Check(w))
1078 ps2 = _PyUnicode_AsString(w);
1079 }
1080 arena = PyArena_New();
1081 if (arena == NULL) {
1082 Py_XDECREF(v);
1083 Py_XDECREF(w);
1084 Py_XDECREF(oenc);
1085 return -1;
1086 }
1087 mod = PyParser_ASTFromFile(fp, filename, enc,
1088 Py_single_input, ps1, ps2,
1089 flags, &errcode, arena);
1090 Py_XDECREF(v);
1091 Py_XDECREF(w);
1092 Py_XDECREF(oenc);
1093 if (mod == NULL) {
1094 PyArena_Free(arena);
1095 if (errcode == E_EOF) {
1096 PyErr_Clear();
1097 return E_EOF;
1098 }
1099 PyErr_Print();
1100 return -1;
1101 }
1102 m = PyImport_AddModule("__main__");
1103 if (m == NULL) {
1104 PyArena_Free(arena);
1105 return -1;
1106 }
1107 d = PyModule_GetDict(m);
1108 v = run_mod(mod, filename, d, d, flags, arena);
1109 PyArena_Free(arena);
1110 flush_io();
1111 if (v == NULL) {
1112 PyErr_Print();
1113 return -1;
1114 }
1115 Py_DECREF(v);
1116 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001117}
1118
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001119/* Check whether a file maybe a pyc file: Look at the extension,
1120 the file type, and, if we may close it, at the first few bytes. */
1121
1122static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001123maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1126 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 /* Only look into the file if we are allowed to close it, since
1129 it then should also be seekable. */
1130 if (closeit) {
1131 /* Read only two bytes of the magic. If the file was opened in
1132 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1133 be read as they are on disk. */
1134 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1135 unsigned char buf[2];
1136 /* Mess: In case of -x, the stream is NOT at its start now,
1137 and ungetc() was used to push back the first newline,
1138 which makes the current stream position formally undefined,
1139 and a x-platform nightmare.
1140 Unfortunately, we have no direct way to know whether -x
1141 was specified. So we use a terrible hack: if the current
1142 stream position is not 0, we assume -x was specified, and
1143 give up. Bug 132850 on SourceForge spells out the
1144 hopelessness of trying anything else (fseek and ftell
1145 don't work predictably x-platform for text-mode files).
1146 */
1147 int ispyc = 0;
1148 if (ftell(fp) == 0) {
1149 if (fread(buf, 1, 2, fp) == 2 &&
1150 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1151 ispyc = 1;
1152 rewind(fp);
1153 }
1154 return ispyc;
1155 }
1156 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001157}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001158
Guido van Rossum0df002c2000-08-27 19:21:52 +00001159int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001160PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 PyObject *m, *d, *v;
1164 const char *ext;
1165 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 m = PyImport_AddModule("__main__");
1168 if (m == NULL)
1169 return -1;
1170 d = PyModule_GetDict(m);
1171 if (PyDict_GetItemString(d, "__file__") == NULL) {
1172 PyObject *f;
1173 f = PyUnicode_DecodeFSDefault(filename);
1174 if (f == NULL)
1175 return -1;
1176 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1177 Py_DECREF(f);
1178 return -1;
1179 }
1180 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1181 return -1;
1182 set_file_name = 1;
1183 Py_DECREF(f);
1184 }
1185 len = strlen(filename);
1186 ext = filename + len - (len > 4 ? 4 : 0);
1187 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1188 /* Try to run a pyc file. First, re-open in binary */
1189 if (closeit)
1190 fclose(fp);
1191 if ((fp = fopen(filename, "rb")) == NULL) {
1192 fprintf(stderr, "python: Can't reopen .pyc file\n");
1193 ret = -1;
1194 goto done;
1195 }
1196 /* Turn on optimization if a .pyo file is given */
1197 if (strcmp(ext, ".pyo") == 0)
1198 Py_OptimizeFlag = 1;
1199 v = run_pyc_file(fp, filename, d, d, flags);
1200 } else {
1201 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1202 closeit, flags);
1203 }
1204 flush_io();
1205 if (v == NULL) {
1206 PyErr_Print();
1207 ret = -1;
1208 goto done;
1209 }
1210 Py_DECREF(v);
1211 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001212 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1214 PyErr_Clear();
1215 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001216}
1217
1218int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001219PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 PyObject *m, *d, *v;
1222 m = PyImport_AddModule("__main__");
1223 if (m == NULL)
1224 return -1;
1225 d = PyModule_GetDict(m);
1226 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1227 if (v == NULL) {
1228 PyErr_Print();
1229 return -1;
1230 }
1231 Py_DECREF(v);
1232 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001233}
1234
Barry Warsaw035574d1997-08-29 22:07:17 +00001235static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001236parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 long hold;
1240 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 /* old style errors */
1243 if (PyTuple_Check(err))
1244 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1245 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 if (! (v = PyObject_GetAttrString(err, "msg")))
1250 goto finally;
1251 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (!(v = PyObject_GetAttrString(err, "filename")))
1254 goto finally;
1255 if (v == Py_None)
1256 *filename = NULL;
1257 else if (! (*filename = _PyUnicode_AsString(v)))
1258 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 Py_DECREF(v);
1261 if (!(v = PyObject_GetAttrString(err, "lineno")))
1262 goto finally;
1263 hold = PyLong_AsLong(v);
1264 Py_DECREF(v);
1265 v = NULL;
1266 if (hold < 0 && PyErr_Occurred())
1267 goto finally;
1268 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (!(v = PyObject_GetAttrString(err, "offset")))
1271 goto finally;
1272 if (v == Py_None) {
1273 *offset = -1;
1274 Py_DECREF(v);
1275 v = NULL;
1276 } else {
1277 hold = PyLong_AsLong(v);
1278 Py_DECREF(v);
1279 v = NULL;
1280 if (hold < 0 && PyErr_Occurred())
1281 goto finally;
1282 *offset = (int)hold;
1283 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 if (!(v = PyObject_GetAttrString(err, "text")))
1286 goto finally;
1287 if (v == Py_None)
1288 *text = NULL;
1289 else if (!PyUnicode_Check(v) ||
1290 !(*text = _PyUnicode_AsString(v)))
1291 goto finally;
1292 Py_DECREF(v);
1293 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001294
1295finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 Py_XDECREF(v);
1297 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001298}
1299
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001300void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001301PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001304}
1305
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001306static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001307print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 char *nl;
1310 if (offset >= 0) {
1311 if (offset > 0 && offset == (int)strlen(text))
1312 offset--;
1313 for (;;) {
1314 nl = strchr(text, '\n');
1315 if (nl == NULL || nl-text >= offset)
1316 break;
1317 offset -= (int)(nl+1-text);
1318 text = nl+1;
1319 }
1320 while (*text == ' ' || *text == '\t') {
1321 text++;
1322 offset--;
1323 }
1324 }
1325 PyFile_WriteString(" ", f);
1326 PyFile_WriteString(text, f);
1327 if (*text == '\0' || text[strlen(text)-1] != '\n')
1328 PyFile_WriteString("\n", f);
1329 if (offset == -1)
1330 return;
1331 PyFile_WriteString(" ", f);
1332 offset--;
1333 while (offset > 0) {
1334 PyFile_WriteString(" ", f);
1335 offset--;
1336 }
1337 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001338}
1339
Guido van Rossum66e8e862001-03-23 17:54:43 +00001340static void
1341handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001342{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 PyObject *exception, *value, *tb;
1344 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 if (Py_InspectFlag)
1347 /* Don't exit if -i flag was given. This flag is set to 0
1348 * when entering interactive mode for inspecting. */
1349 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 PyErr_Fetch(&exception, &value, &tb);
1352 fflush(stdout);
1353 if (value == NULL || value == Py_None)
1354 goto done;
1355 if (PyExceptionInstance_Check(value)) {
1356 /* The error code should be in the `code' attribute. */
1357 PyObject *code = PyObject_GetAttrString(value, "code");
1358 if (code) {
1359 Py_DECREF(value);
1360 value = code;
1361 if (value == Py_None)
1362 goto done;
1363 }
1364 /* If we failed to dig out the 'code' attribute,
1365 just let the else clause below print the error. */
1366 }
1367 if (PyLong_Check(value))
1368 exitcode = (int)PyLong_AsLong(value);
1369 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001370 PyObject *sys_stderr = PySys_GetObject("stderr");
1371 if (sys_stderr != NULL)
1372 PyObject_CallMethod(sys_stderr, "flush", NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 PyObject_Print(value, stderr, Py_PRINT_RAW);
Victor Stinnere9fb3192010-05-17 08:58:51 +00001374 fflush(stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 PySys_WriteStderr("\n");
1376 exitcode = 1;
1377 }
Tim Peterscf615b52003-04-19 18:47:02 +00001378 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 /* Restore and clear the exception info, in order to properly decref
1380 * the exception, value, and traceback. If we just exit instead,
1381 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1382 * some finalizers from running.
1383 */
1384 PyErr_Restore(exception, value, tb);
1385 PyErr_Clear();
1386 Py_Exit(exitcode);
1387 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001388}
1389
1390void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001391PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1396 handle_system_exit();
1397 }
1398 PyErr_Fetch(&exception, &v, &tb);
1399 if (exception == NULL)
1400 return;
1401 PyErr_NormalizeException(&exception, &v, &tb);
1402 if (tb == NULL) {
1403 tb = Py_None;
1404 Py_INCREF(tb);
1405 }
1406 PyException_SetTraceback(v, tb);
1407 if (exception == NULL)
1408 return;
1409 /* Now we know v != NULL too */
1410 if (set_sys_last_vars) {
1411 PySys_SetObject("last_type", exception);
1412 PySys_SetObject("last_value", v);
1413 PySys_SetObject("last_traceback", tb);
1414 }
1415 hook = PySys_GetObject("excepthook");
1416 if (hook) {
1417 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1418 PyObject *result = PyEval_CallObject(hook, args);
1419 if (result == NULL) {
1420 PyObject *exception2, *v2, *tb2;
1421 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1422 handle_system_exit();
1423 }
1424 PyErr_Fetch(&exception2, &v2, &tb2);
1425 PyErr_NormalizeException(&exception2, &v2, &tb2);
1426 /* It should not be possible for exception2 or v2
1427 to be NULL. However PyErr_Display() can't
1428 tolerate NULLs, so just be safe. */
1429 if (exception2 == NULL) {
1430 exception2 = Py_None;
1431 Py_INCREF(exception2);
1432 }
1433 if (v2 == NULL) {
1434 v2 = Py_None;
1435 Py_INCREF(v2);
1436 }
1437 fflush(stdout);
1438 PySys_WriteStderr("Error in sys.excepthook:\n");
1439 PyErr_Display(exception2, v2, tb2);
1440 PySys_WriteStderr("\nOriginal exception was:\n");
1441 PyErr_Display(exception, v, tb);
1442 Py_DECREF(exception2);
1443 Py_DECREF(v2);
1444 Py_XDECREF(tb2);
1445 }
1446 Py_XDECREF(result);
1447 Py_XDECREF(args);
1448 } else {
1449 PySys_WriteStderr("sys.excepthook is missing\n");
1450 PyErr_Display(exception, v, tb);
1451 }
1452 Py_XDECREF(exception);
1453 Py_XDECREF(v);
1454 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001455}
1456
Benjamin Petersone6528212008-07-15 15:32:09 +00001457static void
1458print_exception(PyObject *f, PyObject *value)
1459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 int err = 0;
1461 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (!PyExceptionInstance_Check(value)) {
1464 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1465 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1466 PyFile_WriteString(" found\n", f);
1467 return;
1468 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 Py_INCREF(value);
1471 fflush(stdout);
1472 type = (PyObject *) Py_TYPE(value);
1473 tb = PyException_GetTraceback(value);
1474 if (tb && tb != Py_None)
1475 err = PyTraceBack_Print(tb, f);
1476 if (err == 0 &&
1477 PyObject_HasAttrString(value, "print_file_and_line"))
1478 {
1479 PyObject *message;
1480 const char *filename, *text;
1481 int lineno, offset;
1482 if (!parse_syntax_error(value, &message, &filename,
1483 &lineno, &offset, &text))
1484 PyErr_Clear();
1485 else {
1486 char buf[10];
1487 PyFile_WriteString(" File \"", f);
1488 if (filename == NULL)
1489 PyFile_WriteString("<string>", f);
1490 else
1491 PyFile_WriteString(filename, f);
1492 PyFile_WriteString("\", line ", f);
1493 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1494 PyFile_WriteString(buf, f);
1495 PyFile_WriteString("\n", f);
1496 if (text != NULL)
1497 print_error_text(f, offset, text);
1498 Py_DECREF(value);
1499 value = message;
1500 /* Can't be bothered to check all those
1501 PyFile_WriteString() calls */
1502 if (PyErr_Occurred())
1503 err = -1;
1504 }
1505 }
1506 if (err) {
1507 /* Don't do anything else */
1508 }
1509 else {
1510 PyObject* moduleName;
1511 char* className;
1512 assert(PyExceptionClass_Check(type));
1513 className = PyExceptionClass_Name(type);
1514 if (className != NULL) {
1515 char *dot = strrchr(className, '.');
1516 if (dot != NULL)
1517 className = dot+1;
1518 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 moduleName = PyObject_GetAttrString(type, "__module__");
1521 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1522 {
1523 Py_DECREF(moduleName);
1524 err = PyFile_WriteString("<unknown>", f);
1525 }
1526 else {
1527 char* modstr = _PyUnicode_AsString(moduleName);
1528 if (modstr && strcmp(modstr, "builtins"))
1529 {
1530 err = PyFile_WriteString(modstr, f);
1531 err += PyFile_WriteString(".", f);
1532 }
1533 Py_DECREF(moduleName);
1534 }
1535 if (err == 0) {
1536 if (className == NULL)
1537 err = PyFile_WriteString("<unknown>", f);
1538 else
1539 err = PyFile_WriteString(className, f);
1540 }
1541 }
1542 if (err == 0 && (value != Py_None)) {
1543 PyObject *s = PyObject_Str(value);
1544 /* only print colon if the str() of the
1545 object is not the empty string
1546 */
1547 if (s == NULL)
1548 err = -1;
1549 else if (!PyUnicode_Check(s) ||
1550 PyUnicode_GetSize(s) != 0)
1551 err = PyFile_WriteString(": ", f);
1552 if (err == 0)
1553 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1554 Py_XDECREF(s);
1555 }
1556 /* try to write a newline in any case */
1557 err += PyFile_WriteString("\n", f);
1558 Py_XDECREF(tb);
1559 Py_DECREF(value);
1560 /* If an error happened here, don't show it.
1561 XXX This is wrong, but too many callers rely on this behavior. */
1562 if (err != 0)
1563 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001564}
1565
1566static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 "\nThe above exception was the direct cause "
1568 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001569
1570static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 "\nDuring handling of the above exception, "
1572 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001573
1574static void
1575print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 int err = 0, res;
1578 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 if (seen != NULL) {
1581 /* Exception chaining */
1582 if (PySet_Add(seen, value) == -1)
1583 PyErr_Clear();
1584 else if (PyExceptionInstance_Check(value)) {
1585 cause = PyException_GetCause(value);
1586 context = PyException_GetContext(value);
1587 if (cause) {
1588 res = PySet_Contains(seen, cause);
1589 if (res == -1)
1590 PyErr_Clear();
1591 if (res == 0) {
1592 print_exception_recursive(
1593 f, cause, seen);
1594 err |= PyFile_WriteString(
1595 cause_message, f);
1596 }
1597 }
1598 else if (context) {
1599 res = PySet_Contains(seen, context);
1600 if (res == -1)
1601 PyErr_Clear();
1602 if (res == 0) {
1603 print_exception_recursive(
1604 f, context, seen);
1605 err |= PyFile_WriteString(
1606 context_message, f);
1607 }
1608 }
1609 Py_XDECREF(context);
1610 Py_XDECREF(cause);
1611 }
1612 }
1613 print_exception(f, value);
1614 if (err != 0)
1615 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001616}
1617
Thomas Wouters477c8d52006-05-27 19:21:47 +00001618void
1619PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 PyObject *seen;
1622 PyObject *f = PySys_GetObject("stderr");
1623 if (f == Py_None) {
1624 /* pass */
1625 }
1626 else if (f == NULL) {
1627 _PyObject_Dump(value);
1628 fprintf(stderr, "lost sys.stderr\n");
1629 }
1630 else {
1631 /* We choose to ignore seen being possibly NULL, and report
1632 at least the main exception (it could be a MemoryError).
1633 */
1634 seen = PySet_New(NULL);
1635 if (seen == NULL)
1636 PyErr_Clear();
1637 print_exception_recursive(f, value, seen);
1638 Py_XDECREF(seen);
1639 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001640}
1641
Guido van Rossum82598051997-03-05 00:20:32 +00001642PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001643PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 PyObject *ret = NULL;
1647 mod_ty mod;
1648 PyArena *arena = PyArena_New();
1649 if (arena == NULL)
1650 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1653 if (mod != NULL)
1654 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1655 PyArena_Free(arena);
1656 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001657}
1658
1659PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001660PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 PyObject *ret;
1664 mod_ty mod;
1665 PyArena *arena = PyArena_New();
1666 if (arena == NULL)
1667 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1670 flags, NULL, arena);
1671 if (closeit)
1672 fclose(fp);
1673 if (mod == NULL) {
1674 PyArena_Free(arena);
1675 return NULL;
1676 }
1677 ret = run_mod(mod, filename, globals, locals, flags, arena);
1678 PyArena_Free(arena);
1679 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001680}
1681
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001682static void
1683flush_io(void)
1684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyObject *f, *r;
1686 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 /* Save the current exception */
1689 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 f = PySys_GetObject("stderr");
1692 if (f != NULL) {
1693 r = PyObject_CallMethod(f, "flush", "");
1694 if (r)
1695 Py_DECREF(r);
1696 else
1697 PyErr_Clear();
1698 }
1699 f = PySys_GetObject("stdout");
1700 if (f != NULL) {
1701 r = PyObject_CallMethod(f, "flush", "");
1702 if (r)
1703 Py_DECREF(r);
1704 else
1705 PyErr_Clear();
1706 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001709}
1710
Guido van Rossum82598051997-03-05 00:20:32 +00001711static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001712run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 PyCodeObject *co;
1716 PyObject *v;
1717 co = PyAST_Compile(mod, filename, flags, arena);
1718 if (co == NULL)
1719 return NULL;
1720 v = PyEval_EvalCode(co, globals, locals);
1721 Py_DECREF(co);
1722 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001723}
1724
Guido van Rossum82598051997-03-05 00:20:32 +00001725static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001726run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 PyCodeObject *co;
1730 PyObject *v;
1731 long magic;
1732 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 magic = PyMarshal_ReadLongFromFile(fp);
1735 if (magic != PyImport_GetMagicNumber()) {
1736 PyErr_SetString(PyExc_RuntimeError,
1737 "Bad magic number in .pyc file");
1738 return NULL;
1739 }
1740 (void) PyMarshal_ReadLongFromFile(fp);
1741 v = PyMarshal_ReadLastObjectFromFile(fp);
1742 fclose(fp);
1743 if (v == NULL || !PyCode_Check(v)) {
1744 Py_XDECREF(v);
1745 PyErr_SetString(PyExc_RuntimeError,
1746 "Bad code object in .pyc file");
1747 return NULL;
1748 }
1749 co = (PyCodeObject *)v;
1750 v = PyEval_EvalCode(co, globals, locals);
1751 if (v && flags)
1752 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1753 Py_DECREF(co);
1754 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001755}
1756
Guido van Rossum82598051997-03-05 00:20:32 +00001757PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001758Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 PyCodeObject *co;
1762 mod_ty mod;
1763 PyArena *arena = PyArena_New();
1764 if (arena == NULL)
1765 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1768 if (mod == NULL) {
1769 PyArena_Free(arena);
1770 return NULL;
1771 }
1772 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1773 PyObject *result = PyAST_mod2obj(mod);
1774 PyArena_Free(arena);
1775 return result;
1776 }
1777 co = PyAST_Compile(mod, filename, flags, arena);
1778 PyArena_Free(arena);
1779 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001780}
1781
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001782struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001783Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 struct symtable *st;
1786 mod_ty mod;
1787 PyCompilerFlags flags;
1788 PyArena *arena = PyArena_New();
1789 if (arena == NULL)
1790 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 flags.cf_flags = 0;
1793 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1794 if (mod == NULL) {
1795 PyArena_Free(arena);
1796 return NULL;
1797 }
1798 st = PySymtable_Build(mod, filename, 0);
1799 PyArena_Free(arena);
1800 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001801}
1802
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803/* Preferred access to parser is through AST. */
1804mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001805PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 mod_ty mod;
1809 PyCompilerFlags localflags;
1810 perrdetail err;
1811 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1814 &_PyParser_Grammar, start, &err,
1815 &iflags);
1816 if (flags == NULL) {
1817 localflags.cf_flags = 0;
1818 flags = &localflags;
1819 }
1820 if (n) {
1821 flags->cf_flags |= iflags & PyCF_MASK;
1822 mod = PyAST_FromNode(n, flags, filename, arena);
1823 PyNode_Free(n);
1824 return mod;
1825 }
1826 else {
1827 err_input(&err);
1828 return NULL;
1829 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001830}
1831
1832mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001833PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 int start, char *ps1,
1835 char *ps2, PyCompilerFlags *flags, int *errcode,
1836 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 mod_ty mod;
1839 PyCompilerFlags localflags;
1840 perrdetail err;
1841 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1844 &_PyParser_Grammar,
1845 start, ps1, ps2, &err, &iflags);
1846 if (flags == NULL) {
1847 localflags.cf_flags = 0;
1848 flags = &localflags;
1849 }
1850 if (n) {
1851 flags->cf_flags |= iflags & PyCF_MASK;
1852 mod = PyAST_FromNode(n, flags, filename, arena);
1853 PyNode_Free(n);
1854 return mod;
1855 }
1856 else {
1857 err_input(&err);
1858 if (errcode)
1859 *errcode = err.error;
1860 return NULL;
1861 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001862}
1863
Guido van Rossuma110aa61994-08-29 12:50:44 +00001864/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001865
Guido van Rossuma110aa61994-08-29 12:50:44 +00001866node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001867PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 perrdetail err;
1870 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1871 &_PyParser_Grammar,
1872 start, NULL, NULL, &err, flags);
1873 if (n == NULL)
1874 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001877}
1878
Guido van Rossuma110aa61994-08-29 12:50:44 +00001879/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001880
Guido van Rossuma110aa61994-08-29 12:50:44 +00001881node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001882PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001884 perrdetail err;
1885 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1886 start, &err, flags);
1887 if (n == NULL)
1888 err_input(&err);
1889 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001890}
1891
1892node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001893PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 perrdetail err;
1897 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1898 &_PyParser_Grammar, start, &err, flags);
1899 if (n == NULL)
1900 err_input(&err);
1901 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001902}
1903
1904node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001905PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001908}
1909
Guido van Rossum66ebd912003-04-17 16:02:26 +00001910/* May want to move a more generalized form of this to parsetok.c or
1911 even parser modules. */
1912
1913void
1914PyParser_SetError(perrdetail *err)
1915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001917}
1918
Guido van Rossuma110aa61994-08-29 12:50:44 +00001919/* Set the error appropriate to the given input error code (see errcode.h) */
1920
1921static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001922err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 PyObject *v, *w, *errtype, *errtext;
1925 PyObject *msg_obj = NULL;
1926 char *msg = NULL;
1927 errtype = PyExc_SyntaxError;
1928 switch (err->error) {
1929 case E_ERROR:
1930 return;
1931 case E_SYNTAX:
1932 errtype = PyExc_IndentationError;
1933 if (err->expected == INDENT)
1934 msg = "expected an indented block";
1935 else if (err->token == INDENT)
1936 msg = "unexpected indent";
1937 else if (err->token == DEDENT)
1938 msg = "unexpected unindent";
1939 else {
1940 errtype = PyExc_SyntaxError;
1941 msg = "invalid syntax";
1942 }
1943 break;
1944 case E_TOKEN:
1945 msg = "invalid token";
1946 break;
1947 case E_EOFS:
1948 msg = "EOF while scanning triple-quoted string literal";
1949 break;
1950 case E_EOLS:
1951 msg = "EOL while scanning string literal";
1952 break;
1953 case E_INTR:
1954 if (!PyErr_Occurred())
1955 PyErr_SetNone(PyExc_KeyboardInterrupt);
1956 goto cleanup;
1957 case E_NOMEM:
1958 PyErr_NoMemory();
1959 goto cleanup;
1960 case E_EOF:
1961 msg = "unexpected EOF while parsing";
1962 break;
1963 case E_TABSPACE:
1964 errtype = PyExc_TabError;
1965 msg = "inconsistent use of tabs and spaces in indentation";
1966 break;
1967 case E_OVERFLOW:
1968 msg = "expression too long";
1969 break;
1970 case E_DEDENT:
1971 errtype = PyExc_IndentationError;
1972 msg = "unindent does not match any outer indentation level";
1973 break;
1974 case E_TOODEEP:
1975 errtype = PyExc_IndentationError;
1976 msg = "too many levels of indentation";
1977 break;
1978 case E_DECODE: {
1979 PyObject *type, *value, *tb;
1980 PyErr_Fetch(&type, &value, &tb);
1981 msg = "unknown decode error";
1982 if (value != NULL)
1983 msg_obj = PyObject_Str(value);
1984 Py_XDECREF(type);
1985 Py_XDECREF(value);
1986 Py_XDECREF(tb);
1987 break;
1988 }
1989 case E_LINECONT:
1990 msg = "unexpected character after line continuation character";
1991 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 case E_IDENTIFIER:
1994 msg = "invalid character in identifier";
1995 break;
1996 default:
1997 fprintf(stderr, "error=%d\n", err->error);
1998 msg = "unknown parsing error";
1999 break;
2000 }
2001 /* err->text may not be UTF-8 in case of decoding errors.
2002 Explicitly convert to an object. */
2003 if (!err->text) {
2004 errtext = Py_None;
2005 Py_INCREF(Py_None);
2006 } else {
2007 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2008 "replace");
2009 }
2010 v = Py_BuildValue("(ziiN)", err->filename,
2011 err->lineno, err->offset, errtext);
2012 if (v != NULL) {
2013 if (msg_obj)
2014 w = Py_BuildValue("(OO)", msg_obj, v);
2015 else
2016 w = Py_BuildValue("(sO)", msg, v);
2017 } else
2018 w = NULL;
2019 Py_XDECREF(v);
2020 PyErr_SetObject(errtype, w);
2021 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002022cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 Py_XDECREF(msg_obj);
2024 if (err->text != NULL) {
2025 PyObject_FREE(err->text);
2026 err->text = NULL;
2027 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002028}
2029
2030/* Print fatal error message and abort */
2031
2032void
Tim Peters7c321a82002-07-09 02:57:01 +00002033Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 fprintf(stderr, "Fatal Python error: %s\n", msg);
2036 fflush(stderr); /* it helps in Windows debug build */
2037 if (PyErr_Occurred()) {
2038 PyErr_Print();
2039 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002040#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 {
2042 size_t len = strlen(msg);
2043 WCHAR* buffer;
2044 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 /* Convert the message to wchar_t. This uses a simple one-to-one
2047 conversion, assuming that the this error message actually uses ASCII
2048 only. If this ceases to be true, we will have to convert. */
2049 buffer = alloca( (len+1) * (sizeof *buffer));
2050 for( i=0; i<=len; ++i)
2051 buffer[i] = msg[i];
2052 OutputDebugStringW(L"Fatal Python error: ");
2053 OutputDebugStringW(buffer);
2054 OutputDebugStringW(L"\n");
2055 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002056#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002058#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002059#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002061}
2062
2063/* Clean up and exit */
2064
Guido van Rossuma110aa61994-08-29 12:50:44 +00002065#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002066#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002067#endif
2068
Collin Winter670e6922007-03-21 02:57:17 +00002069static void (*pyexitfunc)(void) = NULL;
2070/* For the atexit module. */
2071void _Py_PyAtExit(void (*func)(void))
2072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002074}
2075
2076static void
2077call_py_exitfuncs(void)
2078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 if (pyexitfunc == NULL)
2080 return;
Collin Winter670e6922007-03-21 02:57:17 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 (*pyexitfunc)();
2083 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002084}
2085
Antoine Pitrou011bd622009-10-20 21:52:47 +00002086/* Wait until threading._shutdown completes, provided
2087 the threading module was imported in the first place.
2088 The shutdown routine will wait until all non-daemon
2089 "threading" threads have completed. */
2090static void
2091wait_for_thread_shutdown(void)
2092{
2093#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 PyObject *result;
2095 PyThreadState *tstate = PyThreadState_GET();
2096 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2097 "threading");
2098 if (threading == NULL) {
2099 /* threading not imported */
2100 PyErr_Clear();
2101 return;
2102 }
2103 result = PyObject_CallMethod(threading, "_shutdown", "");
2104 if (result == NULL) {
2105 PyErr_WriteUnraisable(threading);
2106 }
2107 else {
2108 Py_DECREF(result);
2109 }
2110 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002111#endif
2112}
2113
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002114#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002115static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002116static int nexitfuncs = 0;
2117
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002118int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 if (nexitfuncs >= NEXITFUNCS)
2121 return -1;
2122 exitfuncs[nexitfuncs++] = func;
2123 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002124}
2125
Guido van Rossumcc283f51997-08-05 02:22:03 +00002126static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002127call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 while (nexitfuncs > 0)
2130 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 fflush(stdout);
2133 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002134}
2135
2136void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002137Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002142}
2143
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002144static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002145initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002146{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002147#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002149#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002150#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002152#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002153#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002155#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002157}
2158
Guido van Rossum7433b121997-02-14 19:45:36 +00002159
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002160/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2161 *
2162 * All of the code in this function must only use async-signal-safe functions,
2163 * listed at `man 7 signal` or
2164 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2165 */
2166void
2167_Py_RestoreSignals(void)
2168{
2169#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002171#endif
2172#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002174#endif
2175#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002177#endif
2178}
2179
2180
Guido van Rossum7433b121997-02-14 19:45:36 +00002181/*
2182 * The file descriptor fd is considered ``interactive'' if either
2183 * a) isatty(fd) is TRUE, or
2184 * b) the -i flag was given, and the filename associated with
2185 * the descriptor is NULL or "<stdin>" or "???".
2186 */
2187int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002188Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if (isatty((int)fileno(fp)))
2191 return 1;
2192 if (!Py_InteractiveFlag)
2193 return 0;
2194 return (filename == NULL) ||
2195 (strcmp(filename, "<stdin>") == 0) ||
2196 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002197}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002198
2199
Tim Petersd08e3822003-04-17 15:24:21 +00002200#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002201#if defined(WIN32) && defined(_MSC_VER)
2202
2203/* Stack checking for Microsoft C */
2204
2205#include <malloc.h>
2206#include <excpt.h>
2207
Fred Drakee8de31c2000-08-31 05:38:39 +00002208/*
2209 * Return non-zero when we run out of memory on the stack; zero otherwise.
2210 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002211int
Fred Drake399739f2000-08-31 05:52:44 +00002212PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 __try {
2215 /* alloca throws a stack overflow exception if there's
2216 not enough space left on the stack */
2217 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2218 return 0;
2219 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2220 EXCEPTION_EXECUTE_HANDLER :
2221 EXCEPTION_CONTINUE_SEARCH) {
2222 int errcode = _resetstkoflw();
2223 if (errcode == 0)
2224 {
2225 Py_FatalError("Could not reset the stack!");
2226 }
2227 }
2228 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002229}
2230
2231#endif /* WIN32 && _MSC_VER */
2232
2233/* Alternate implementations can be added here... */
2234
2235#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002236
2237
2238/* Wrappers around sigaction() or signal(). */
2239
2240PyOS_sighandler_t
2241PyOS_getsig(int sig)
2242{
2243#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 struct sigaction context;
2245 if (sigaction(sig, NULL, &context) == -1)
2246 return SIG_ERR;
2247 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002248#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002250/* Special signal handling for the secure CRT in Visual Studio 2005 */
2251#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 switch (sig) {
2253 /* Only these signals are valid */
2254 case SIGINT:
2255 case SIGILL:
2256 case SIGFPE:
2257 case SIGSEGV:
2258 case SIGTERM:
2259 case SIGBREAK:
2260 case SIGABRT:
2261 break;
2262 /* Don't call signal() with other values or it will assert */
2263 default:
2264 return SIG_ERR;
2265 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002266#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 handler = signal(sig, SIG_IGN);
2268 if (handler != SIG_ERR)
2269 signal(sig, handler);
2270 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002271#endif
2272}
2273
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002274/*
2275 * All of the code in this function must only use async-signal-safe functions,
2276 * listed at `man 7 signal` or
2277 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2278 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002279PyOS_sighandler_t
2280PyOS_setsig(int sig, PyOS_sighandler_t handler)
2281{
2282#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* Some code in Modules/signalmodule.c depends on sigaction() being
2284 * used here if HAVE_SIGACTION is defined. Fix that if this code
2285 * changes to invalidate that assumption.
2286 */
2287 struct sigaction context, ocontext;
2288 context.sa_handler = handler;
2289 sigemptyset(&context.sa_mask);
2290 context.sa_flags = 0;
2291 if (sigaction(sig, &context, &ocontext) == -1)
2292 return SIG_ERR;
2293 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002294#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 PyOS_sighandler_t oldhandler;
2296 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002297#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002299#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002301#endif
2302}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303
2304/* Deprecated C API functions still provided for binary compatiblity */
2305
2306#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002307PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002308PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311}
2312
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002313#undef PyParser_SimpleParseString
2314PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002315PyParser_SimpleParseString(const char *str, int start)
2316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002318}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002319
2320#undef PyRun_AnyFile
2321PyAPI_FUNC(int)
2322PyRun_AnyFile(FILE *fp, const char *name)
2323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002325}
2326
2327#undef PyRun_AnyFileEx
2328PyAPI_FUNC(int)
2329PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002332}
2333
2334#undef PyRun_AnyFileFlags
2335PyAPI_FUNC(int)
2336PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002339}
2340
2341#undef PyRun_File
2342PyAPI_FUNC(PyObject *)
2343PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002346}
2347
2348#undef PyRun_FileEx
2349PyAPI_FUNC(PyObject *)
2350PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002353}
2354
2355#undef PyRun_FileFlags
2356PyAPI_FUNC(PyObject *)
2357PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002361}
2362
2363#undef PyRun_SimpleFile
2364PyAPI_FUNC(int)
2365PyRun_SimpleFile(FILE *f, const char *p)
2366{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002368}
2369
2370#undef PyRun_SimpleFileEx
2371PyAPI_FUNC(int)
2372PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002375}
2376
2377
2378#undef PyRun_String
2379PyAPI_FUNC(PyObject *)
2380PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002383}
2384
2385#undef PyRun_SimpleString
2386PyAPI_FUNC(int)
2387PyRun_SimpleString(const char *s)
2388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002390}
2391
2392#undef Py_CompileString
2393PyAPI_FUNC(PyObject *)
2394Py_CompileString(const char *str, const char *p, int s)
2395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002397}
2398
2399#undef PyRun_InteractiveOne
2400PyAPI_FUNC(int)
2401PyRun_InteractiveOne(FILE *f, const char *p)
2402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002404}
2405
2406#undef PyRun_InteractiveLoop
2407PyAPI_FUNC(int)
2408PyRun_InteractiveLoop(FILE *f, const char *p)
2409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002411}
2412
2413#ifdef __cplusplus
2414}
2415#endif