blob: 4932c4ad4c60688fb078ee5670f7897f41dfdf93 [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 {
1370 PyObject_Print(value, stderr, Py_PRINT_RAW);
1371 PySys_WriteStderr("\n");
1372 exitcode = 1;
1373 }
Tim Peterscf615b52003-04-19 18:47:02 +00001374 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 /* Restore and clear the exception info, in order to properly decref
1376 * the exception, value, and traceback. If we just exit instead,
1377 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1378 * some finalizers from running.
1379 */
1380 PyErr_Restore(exception, value, tb);
1381 PyErr_Clear();
1382 Py_Exit(exitcode);
1383 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001384}
1385
1386void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001387PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1392 handle_system_exit();
1393 }
1394 PyErr_Fetch(&exception, &v, &tb);
1395 if (exception == NULL)
1396 return;
1397 PyErr_NormalizeException(&exception, &v, &tb);
1398 if (tb == NULL) {
1399 tb = Py_None;
1400 Py_INCREF(tb);
1401 }
1402 PyException_SetTraceback(v, tb);
1403 if (exception == NULL)
1404 return;
1405 /* Now we know v != NULL too */
1406 if (set_sys_last_vars) {
1407 PySys_SetObject("last_type", exception);
1408 PySys_SetObject("last_value", v);
1409 PySys_SetObject("last_traceback", tb);
1410 }
1411 hook = PySys_GetObject("excepthook");
1412 if (hook) {
1413 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1414 PyObject *result = PyEval_CallObject(hook, args);
1415 if (result == NULL) {
1416 PyObject *exception2, *v2, *tb2;
1417 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1418 handle_system_exit();
1419 }
1420 PyErr_Fetch(&exception2, &v2, &tb2);
1421 PyErr_NormalizeException(&exception2, &v2, &tb2);
1422 /* It should not be possible for exception2 or v2
1423 to be NULL. However PyErr_Display() can't
1424 tolerate NULLs, so just be safe. */
1425 if (exception2 == NULL) {
1426 exception2 = Py_None;
1427 Py_INCREF(exception2);
1428 }
1429 if (v2 == NULL) {
1430 v2 = Py_None;
1431 Py_INCREF(v2);
1432 }
1433 fflush(stdout);
1434 PySys_WriteStderr("Error in sys.excepthook:\n");
1435 PyErr_Display(exception2, v2, tb2);
1436 PySys_WriteStderr("\nOriginal exception was:\n");
1437 PyErr_Display(exception, v, tb);
1438 Py_DECREF(exception2);
1439 Py_DECREF(v2);
1440 Py_XDECREF(tb2);
1441 }
1442 Py_XDECREF(result);
1443 Py_XDECREF(args);
1444 } else {
1445 PySys_WriteStderr("sys.excepthook is missing\n");
1446 PyErr_Display(exception, v, tb);
1447 }
1448 Py_XDECREF(exception);
1449 Py_XDECREF(v);
1450 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001451}
1452
Benjamin Petersone6528212008-07-15 15:32:09 +00001453static void
1454print_exception(PyObject *f, PyObject *value)
1455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 int err = 0;
1457 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (!PyExceptionInstance_Check(value)) {
1460 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1461 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1462 PyFile_WriteString(" found\n", f);
1463 return;
1464 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 Py_INCREF(value);
1467 fflush(stdout);
1468 type = (PyObject *) Py_TYPE(value);
1469 tb = PyException_GetTraceback(value);
1470 if (tb && tb != Py_None)
1471 err = PyTraceBack_Print(tb, f);
1472 if (err == 0 &&
1473 PyObject_HasAttrString(value, "print_file_and_line"))
1474 {
1475 PyObject *message;
1476 const char *filename, *text;
1477 int lineno, offset;
1478 if (!parse_syntax_error(value, &message, &filename,
1479 &lineno, &offset, &text))
1480 PyErr_Clear();
1481 else {
1482 char buf[10];
1483 PyFile_WriteString(" File \"", f);
1484 if (filename == NULL)
1485 PyFile_WriteString("<string>", f);
1486 else
1487 PyFile_WriteString(filename, f);
1488 PyFile_WriteString("\", line ", f);
1489 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1490 PyFile_WriteString(buf, f);
1491 PyFile_WriteString("\n", f);
1492 if (text != NULL)
1493 print_error_text(f, offset, text);
1494 Py_DECREF(value);
1495 value = message;
1496 /* Can't be bothered to check all those
1497 PyFile_WriteString() calls */
1498 if (PyErr_Occurred())
1499 err = -1;
1500 }
1501 }
1502 if (err) {
1503 /* Don't do anything else */
1504 }
1505 else {
1506 PyObject* moduleName;
1507 char* className;
1508 assert(PyExceptionClass_Check(type));
1509 className = PyExceptionClass_Name(type);
1510 if (className != NULL) {
1511 char *dot = strrchr(className, '.');
1512 if (dot != NULL)
1513 className = dot+1;
1514 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 moduleName = PyObject_GetAttrString(type, "__module__");
1517 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1518 {
1519 Py_DECREF(moduleName);
1520 err = PyFile_WriteString("<unknown>", f);
1521 }
1522 else {
1523 char* modstr = _PyUnicode_AsString(moduleName);
1524 if (modstr && strcmp(modstr, "builtins"))
1525 {
1526 err = PyFile_WriteString(modstr, f);
1527 err += PyFile_WriteString(".", f);
1528 }
1529 Py_DECREF(moduleName);
1530 }
1531 if (err == 0) {
1532 if (className == NULL)
1533 err = PyFile_WriteString("<unknown>", f);
1534 else
1535 err = PyFile_WriteString(className, f);
1536 }
1537 }
1538 if (err == 0 && (value != Py_None)) {
1539 PyObject *s = PyObject_Str(value);
1540 /* only print colon if the str() of the
1541 object is not the empty string
1542 */
1543 if (s == NULL)
1544 err = -1;
1545 else if (!PyUnicode_Check(s) ||
1546 PyUnicode_GetSize(s) != 0)
1547 err = PyFile_WriteString(": ", f);
1548 if (err == 0)
1549 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1550 Py_XDECREF(s);
1551 }
1552 /* try to write a newline in any case */
1553 err += PyFile_WriteString("\n", f);
1554 Py_XDECREF(tb);
1555 Py_DECREF(value);
1556 /* If an error happened here, don't show it.
1557 XXX This is wrong, but too many callers rely on this behavior. */
1558 if (err != 0)
1559 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001560}
1561
1562static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 "\nThe above exception was the direct cause "
1564 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001565
1566static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 "\nDuring handling of the above exception, "
1568 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001569
1570static void
1571print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 int err = 0, res;
1574 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (seen != NULL) {
1577 /* Exception chaining */
1578 if (PySet_Add(seen, value) == -1)
1579 PyErr_Clear();
1580 else if (PyExceptionInstance_Check(value)) {
1581 cause = PyException_GetCause(value);
1582 context = PyException_GetContext(value);
1583 if (cause) {
1584 res = PySet_Contains(seen, cause);
1585 if (res == -1)
1586 PyErr_Clear();
1587 if (res == 0) {
1588 print_exception_recursive(
1589 f, cause, seen);
1590 err |= PyFile_WriteString(
1591 cause_message, f);
1592 }
1593 }
1594 else if (context) {
1595 res = PySet_Contains(seen, context);
1596 if (res == -1)
1597 PyErr_Clear();
1598 if (res == 0) {
1599 print_exception_recursive(
1600 f, context, seen);
1601 err |= PyFile_WriteString(
1602 context_message, f);
1603 }
1604 }
1605 Py_XDECREF(context);
1606 Py_XDECREF(cause);
1607 }
1608 }
1609 print_exception(f, value);
1610 if (err != 0)
1611 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001612}
1613
Thomas Wouters477c8d52006-05-27 19:21:47 +00001614void
1615PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 PyObject *seen;
1618 PyObject *f = PySys_GetObject("stderr");
1619 if (f == Py_None) {
1620 /* pass */
1621 }
1622 else if (f == NULL) {
1623 _PyObject_Dump(value);
1624 fprintf(stderr, "lost sys.stderr\n");
1625 }
1626 else {
1627 /* We choose to ignore seen being possibly NULL, and report
1628 at least the main exception (it could be a MemoryError).
1629 */
1630 seen = PySet_New(NULL);
1631 if (seen == NULL)
1632 PyErr_Clear();
1633 print_exception_recursive(f, value, seen);
1634 Py_XDECREF(seen);
1635 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001636}
1637
Guido van Rossum82598051997-03-05 00:20:32 +00001638PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001639PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 PyObject *ret = NULL;
1643 mod_ty mod;
1644 PyArena *arena = PyArena_New();
1645 if (arena == NULL)
1646 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1649 if (mod != NULL)
1650 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1651 PyArena_Free(arena);
1652 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001653}
1654
1655PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001656PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 PyObject *ret;
1660 mod_ty mod;
1661 PyArena *arena = PyArena_New();
1662 if (arena == NULL)
1663 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1666 flags, NULL, arena);
1667 if (closeit)
1668 fclose(fp);
1669 if (mod == NULL) {
1670 PyArena_Free(arena);
1671 return NULL;
1672 }
1673 ret = run_mod(mod, filename, globals, locals, flags, arena);
1674 PyArena_Free(arena);
1675 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001676}
1677
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001678static void
1679flush_io(void)
1680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 PyObject *f, *r;
1682 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 /* Save the current exception */
1685 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 f = PySys_GetObject("stderr");
1688 if (f != NULL) {
1689 r = PyObject_CallMethod(f, "flush", "");
1690 if (r)
1691 Py_DECREF(r);
1692 else
1693 PyErr_Clear();
1694 }
1695 f = PySys_GetObject("stdout");
1696 if (f != NULL) {
1697 r = PyObject_CallMethod(f, "flush", "");
1698 if (r)
1699 Py_DECREF(r);
1700 else
1701 PyErr_Clear();
1702 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001705}
1706
Guido van Rossum82598051997-03-05 00:20:32 +00001707static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 PyCodeObject *co;
1712 PyObject *v;
1713 co = PyAST_Compile(mod, filename, flags, arena);
1714 if (co == NULL)
1715 return NULL;
1716 v = PyEval_EvalCode(co, globals, locals);
1717 Py_DECREF(co);
1718 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001719}
1720
Guido van Rossum82598051997-03-05 00:20:32 +00001721static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001722run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 PyCodeObject *co;
1726 PyObject *v;
1727 long magic;
1728 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 magic = PyMarshal_ReadLongFromFile(fp);
1731 if (magic != PyImport_GetMagicNumber()) {
1732 PyErr_SetString(PyExc_RuntimeError,
1733 "Bad magic number in .pyc file");
1734 return NULL;
1735 }
1736 (void) PyMarshal_ReadLongFromFile(fp);
1737 v = PyMarshal_ReadLastObjectFromFile(fp);
1738 fclose(fp);
1739 if (v == NULL || !PyCode_Check(v)) {
1740 Py_XDECREF(v);
1741 PyErr_SetString(PyExc_RuntimeError,
1742 "Bad code object in .pyc file");
1743 return NULL;
1744 }
1745 co = (PyCodeObject *)v;
1746 v = PyEval_EvalCode(co, globals, locals);
1747 if (v && flags)
1748 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1749 Py_DECREF(co);
1750 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001751}
1752
Guido van Rossum82598051997-03-05 00:20:32 +00001753PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001754Py_CompileStringFlags(const char *str, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyCodeObject *co;
1758 mod_ty mod;
1759 PyArena *arena = PyArena_New();
1760 if (arena == NULL)
1761 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1764 if (mod == NULL) {
1765 PyArena_Free(arena);
1766 return NULL;
1767 }
1768 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1769 PyObject *result = PyAST_mod2obj(mod);
1770 PyArena_Free(arena);
1771 return result;
1772 }
1773 co = PyAST_Compile(mod, filename, flags, arena);
1774 PyArena_Free(arena);
1775 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001776}
1777
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001778struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001779Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 struct symtable *st;
1782 mod_ty mod;
1783 PyCompilerFlags flags;
1784 PyArena *arena = PyArena_New();
1785 if (arena == NULL)
1786 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 flags.cf_flags = 0;
1789 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1790 if (mod == NULL) {
1791 PyArena_Free(arena);
1792 return NULL;
1793 }
1794 st = PySymtable_Build(mod, filename, 0);
1795 PyArena_Free(arena);
1796 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001797}
1798
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799/* Preferred access to parser is through AST. */
1800mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001801PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 mod_ty mod;
1805 PyCompilerFlags localflags;
1806 perrdetail err;
1807 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1810 &_PyParser_Grammar, start, &err,
1811 &iflags);
1812 if (flags == NULL) {
1813 localflags.cf_flags = 0;
1814 flags = &localflags;
1815 }
1816 if (n) {
1817 flags->cf_flags |= iflags & PyCF_MASK;
1818 mod = PyAST_FromNode(n, flags, filename, arena);
1819 PyNode_Free(n);
1820 return mod;
1821 }
1822 else {
1823 err_input(&err);
1824 return NULL;
1825 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001826}
1827
1828mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001829PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 int start, char *ps1,
1831 char *ps2, PyCompilerFlags *flags, int *errcode,
1832 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 mod_ty mod;
1835 PyCompilerFlags localflags;
1836 perrdetail err;
1837 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001839 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1840 &_PyParser_Grammar,
1841 start, ps1, ps2, &err, &iflags);
1842 if (flags == NULL) {
1843 localflags.cf_flags = 0;
1844 flags = &localflags;
1845 }
1846 if (n) {
1847 flags->cf_flags |= iflags & PyCF_MASK;
1848 mod = PyAST_FromNode(n, flags, filename, arena);
1849 PyNode_Free(n);
1850 return mod;
1851 }
1852 else {
1853 err_input(&err);
1854 if (errcode)
1855 *errcode = err.error;
1856 return NULL;
1857 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001858}
1859
Guido van Rossuma110aa61994-08-29 12:50:44 +00001860/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001861
Guido van Rossuma110aa61994-08-29 12:50:44 +00001862node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001863PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 perrdetail err;
1866 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1867 &_PyParser_Grammar,
1868 start, NULL, NULL, &err, flags);
1869 if (n == NULL)
1870 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001873}
1874
Guido van Rossuma110aa61994-08-29 12:50:44 +00001875/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001876
Guido van Rossuma110aa61994-08-29 12:50:44 +00001877node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001878PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 perrdetail err;
1881 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1882 start, &err, flags);
1883 if (n == NULL)
1884 err_input(&err);
1885 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001886}
1887
1888node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001889PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 perrdetail err;
1893 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1894 &_PyParser_Grammar, start, &err, flags);
1895 if (n == NULL)
1896 err_input(&err);
1897 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001898}
1899
1900node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001901PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001904}
1905
Guido van Rossum66ebd912003-04-17 16:02:26 +00001906/* May want to move a more generalized form of this to parsetok.c or
1907 even parser modules. */
1908
1909void
1910PyParser_SetError(perrdetail *err)
1911{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001913}
1914
Guido van Rossuma110aa61994-08-29 12:50:44 +00001915/* Set the error appropriate to the given input error code (see errcode.h) */
1916
1917static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001918err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 PyObject *v, *w, *errtype, *errtext;
1921 PyObject *msg_obj = NULL;
1922 char *msg = NULL;
1923 errtype = PyExc_SyntaxError;
1924 switch (err->error) {
1925 case E_ERROR:
1926 return;
1927 case E_SYNTAX:
1928 errtype = PyExc_IndentationError;
1929 if (err->expected == INDENT)
1930 msg = "expected an indented block";
1931 else if (err->token == INDENT)
1932 msg = "unexpected indent";
1933 else if (err->token == DEDENT)
1934 msg = "unexpected unindent";
1935 else {
1936 errtype = PyExc_SyntaxError;
1937 msg = "invalid syntax";
1938 }
1939 break;
1940 case E_TOKEN:
1941 msg = "invalid token";
1942 break;
1943 case E_EOFS:
1944 msg = "EOF while scanning triple-quoted string literal";
1945 break;
1946 case E_EOLS:
1947 msg = "EOL while scanning string literal";
1948 break;
1949 case E_INTR:
1950 if (!PyErr_Occurred())
1951 PyErr_SetNone(PyExc_KeyboardInterrupt);
1952 goto cleanup;
1953 case E_NOMEM:
1954 PyErr_NoMemory();
1955 goto cleanup;
1956 case E_EOF:
1957 msg = "unexpected EOF while parsing";
1958 break;
1959 case E_TABSPACE:
1960 errtype = PyExc_TabError;
1961 msg = "inconsistent use of tabs and spaces in indentation";
1962 break;
1963 case E_OVERFLOW:
1964 msg = "expression too long";
1965 break;
1966 case E_DEDENT:
1967 errtype = PyExc_IndentationError;
1968 msg = "unindent does not match any outer indentation level";
1969 break;
1970 case E_TOODEEP:
1971 errtype = PyExc_IndentationError;
1972 msg = "too many levels of indentation";
1973 break;
1974 case E_DECODE: {
1975 PyObject *type, *value, *tb;
1976 PyErr_Fetch(&type, &value, &tb);
1977 msg = "unknown decode error";
1978 if (value != NULL)
1979 msg_obj = PyObject_Str(value);
1980 Py_XDECREF(type);
1981 Py_XDECREF(value);
1982 Py_XDECREF(tb);
1983 break;
1984 }
1985 case E_LINECONT:
1986 msg = "unexpected character after line continuation character";
1987 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 case E_IDENTIFIER:
1990 msg = "invalid character in identifier";
1991 break;
1992 default:
1993 fprintf(stderr, "error=%d\n", err->error);
1994 msg = "unknown parsing error";
1995 break;
1996 }
1997 /* err->text may not be UTF-8 in case of decoding errors.
1998 Explicitly convert to an object. */
1999 if (!err->text) {
2000 errtext = Py_None;
2001 Py_INCREF(Py_None);
2002 } else {
2003 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2004 "replace");
2005 }
2006 v = Py_BuildValue("(ziiN)", err->filename,
2007 err->lineno, err->offset, errtext);
2008 if (v != NULL) {
2009 if (msg_obj)
2010 w = Py_BuildValue("(OO)", msg_obj, v);
2011 else
2012 w = Py_BuildValue("(sO)", msg, v);
2013 } else
2014 w = NULL;
2015 Py_XDECREF(v);
2016 PyErr_SetObject(errtype, w);
2017 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002018cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 Py_XDECREF(msg_obj);
2020 if (err->text != NULL) {
2021 PyObject_FREE(err->text);
2022 err->text = NULL;
2023 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002024}
2025
2026/* Print fatal error message and abort */
2027
2028void
Tim Peters7c321a82002-07-09 02:57:01 +00002029Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 fprintf(stderr, "Fatal Python error: %s\n", msg);
2032 fflush(stderr); /* it helps in Windows debug build */
2033 if (PyErr_Occurred()) {
2034 PyErr_Print();
2035 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002036#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 {
2038 size_t len = strlen(msg);
2039 WCHAR* buffer;
2040 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 /* Convert the message to wchar_t. This uses a simple one-to-one
2043 conversion, assuming that the this error message actually uses ASCII
2044 only. If this ceases to be true, we will have to convert. */
2045 buffer = alloca( (len+1) * (sizeof *buffer));
2046 for( i=0; i<=len; ++i)
2047 buffer[i] = msg[i];
2048 OutputDebugStringW(L"Fatal Python error: ");
2049 OutputDebugStringW(buffer);
2050 OutputDebugStringW(L"\n");
2051 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002052#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002054#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002055#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002057}
2058
2059/* Clean up and exit */
2060
Guido van Rossuma110aa61994-08-29 12:50:44 +00002061#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002062#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002063#endif
2064
Collin Winter670e6922007-03-21 02:57:17 +00002065static void (*pyexitfunc)(void) = NULL;
2066/* For the atexit module. */
2067void _Py_PyAtExit(void (*func)(void))
2068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002070}
2071
2072static void
2073call_py_exitfuncs(void)
2074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (pyexitfunc == NULL)
2076 return;
Collin Winter670e6922007-03-21 02:57:17 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 (*pyexitfunc)();
2079 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002080}
2081
Antoine Pitrou011bd622009-10-20 21:52:47 +00002082/* Wait until threading._shutdown completes, provided
2083 the threading module was imported in the first place.
2084 The shutdown routine will wait until all non-daemon
2085 "threading" threads have completed. */
2086static void
2087wait_for_thread_shutdown(void)
2088{
2089#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 PyObject *result;
2091 PyThreadState *tstate = PyThreadState_GET();
2092 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2093 "threading");
2094 if (threading == NULL) {
2095 /* threading not imported */
2096 PyErr_Clear();
2097 return;
2098 }
2099 result = PyObject_CallMethod(threading, "_shutdown", "");
2100 if (result == NULL) {
2101 PyErr_WriteUnraisable(threading);
2102 }
2103 else {
2104 Py_DECREF(result);
2105 }
2106 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002107#endif
2108}
2109
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002110#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002111static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002112static int nexitfuncs = 0;
2113
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002114int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 if (nexitfuncs >= NEXITFUNCS)
2117 return -1;
2118 exitfuncs[nexitfuncs++] = func;
2119 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002120}
2121
Guido van Rossumcc283f51997-08-05 02:22:03 +00002122static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002123call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 while (nexitfuncs > 0)
2126 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 fflush(stdout);
2129 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002130}
2131
2132void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002133Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002138}
2139
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002140static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002141initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002142{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002143#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002145#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002146#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002148#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002149#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002151#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002153}
2154
Guido van Rossum7433b121997-02-14 19:45:36 +00002155
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002156/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2157 *
2158 * All of the code in this function must only use async-signal-safe functions,
2159 * listed at `man 7 signal` or
2160 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2161 */
2162void
2163_Py_RestoreSignals(void)
2164{
2165#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002167#endif
2168#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002170#endif
2171#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002173#endif
2174}
2175
2176
Guido van Rossum7433b121997-02-14 19:45:36 +00002177/*
2178 * The file descriptor fd is considered ``interactive'' if either
2179 * a) isatty(fd) is TRUE, or
2180 * b) the -i flag was given, and the filename associated with
2181 * the descriptor is NULL or "<stdin>" or "???".
2182 */
2183int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002184Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (isatty((int)fileno(fp)))
2187 return 1;
2188 if (!Py_InteractiveFlag)
2189 return 0;
2190 return (filename == NULL) ||
2191 (strcmp(filename, "<stdin>") == 0) ||
2192 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002193}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002194
2195
Tim Petersd08e3822003-04-17 15:24:21 +00002196#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002197#if defined(WIN32) && defined(_MSC_VER)
2198
2199/* Stack checking for Microsoft C */
2200
2201#include <malloc.h>
2202#include <excpt.h>
2203
Fred Drakee8de31c2000-08-31 05:38:39 +00002204/*
2205 * Return non-zero when we run out of memory on the stack; zero otherwise.
2206 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002207int
Fred Drake399739f2000-08-31 05:52:44 +00002208PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 __try {
2211 /* alloca throws a stack overflow exception if there's
2212 not enough space left on the stack */
2213 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2214 return 0;
2215 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2216 EXCEPTION_EXECUTE_HANDLER :
2217 EXCEPTION_CONTINUE_SEARCH) {
2218 int errcode = _resetstkoflw();
2219 if (errcode == 0)
2220 {
2221 Py_FatalError("Could not reset the stack!");
2222 }
2223 }
2224 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002225}
2226
2227#endif /* WIN32 && _MSC_VER */
2228
2229/* Alternate implementations can be added here... */
2230
2231#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002232
2233
2234/* Wrappers around sigaction() or signal(). */
2235
2236PyOS_sighandler_t
2237PyOS_getsig(int sig)
2238{
2239#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 struct sigaction context;
2241 if (sigaction(sig, NULL, &context) == -1)
2242 return SIG_ERR;
2243 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002244#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002246/* Special signal handling for the secure CRT in Visual Studio 2005 */
2247#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 switch (sig) {
2249 /* Only these signals are valid */
2250 case SIGINT:
2251 case SIGILL:
2252 case SIGFPE:
2253 case SIGSEGV:
2254 case SIGTERM:
2255 case SIGBREAK:
2256 case SIGABRT:
2257 break;
2258 /* Don't call signal() with other values or it will assert */
2259 default:
2260 return SIG_ERR;
2261 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002262#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 handler = signal(sig, SIG_IGN);
2264 if (handler != SIG_ERR)
2265 signal(sig, handler);
2266 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002267#endif
2268}
2269
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002270/*
2271 * All of the code in this function must only use async-signal-safe functions,
2272 * listed at `man 7 signal` or
2273 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2274 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002275PyOS_sighandler_t
2276PyOS_setsig(int sig, PyOS_sighandler_t handler)
2277{
2278#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 /* Some code in Modules/signalmodule.c depends on sigaction() being
2280 * used here if HAVE_SIGACTION is defined. Fix that if this code
2281 * changes to invalidate that assumption.
2282 */
2283 struct sigaction context, ocontext;
2284 context.sa_handler = handler;
2285 sigemptyset(&context.sa_mask);
2286 context.sa_flags = 0;
2287 if (sigaction(sig, &context, &ocontext) == -1)
2288 return SIG_ERR;
2289 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002290#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 PyOS_sighandler_t oldhandler;
2292 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002293#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002295#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002297#endif
2298}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002299
2300/* Deprecated C API functions still provided for binary compatiblity */
2301
2302#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002303PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002304PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002307}
2308
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002309#undef PyParser_SimpleParseString
2310PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002311PyParser_SimpleParseString(const char *str, int start)
2312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002314}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002315
2316#undef PyRun_AnyFile
2317PyAPI_FUNC(int)
2318PyRun_AnyFile(FILE *fp, const char *name)
2319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002321}
2322
2323#undef PyRun_AnyFileEx
2324PyAPI_FUNC(int)
2325PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002328}
2329
2330#undef PyRun_AnyFileFlags
2331PyAPI_FUNC(int)
2332PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002335}
2336
2337#undef PyRun_File
2338PyAPI_FUNC(PyObject *)
2339PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002342}
2343
2344#undef PyRun_FileEx
2345PyAPI_FUNC(PyObject *)
2346PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002348 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002349}
2350
2351#undef PyRun_FileFlags
2352PyAPI_FUNC(PyObject *)
2353PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002357}
2358
2359#undef PyRun_SimpleFile
2360PyAPI_FUNC(int)
2361PyRun_SimpleFile(FILE *f, const char *p)
2362{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002364}
2365
2366#undef PyRun_SimpleFileEx
2367PyAPI_FUNC(int)
2368PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002371}
2372
2373
2374#undef PyRun_String
2375PyAPI_FUNC(PyObject *)
2376PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002379}
2380
2381#undef PyRun_SimpleString
2382PyAPI_FUNC(int)
2383PyRun_SimpleString(const char *s)
2384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002386}
2387
2388#undef Py_CompileString
2389PyAPI_FUNC(PyObject *)
2390Py_CompileString(const char *str, const char *p, int s)
2391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 return Py_CompileStringFlags(str, p, s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002393}
2394
2395#undef PyRun_InteractiveOne
2396PyAPI_FUNC(int)
2397PyRun_InteractiveOne(FILE *f, const char *p)
2398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002400}
2401
2402#undef PyRun_InteractiveLoop
2403PyAPI_FUNC(int)
2404PyRun_InteractiveLoop(FILE *f, const char *p)
2405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002407}
2408
2409#ifdef __cplusplus
2410}
2411#endif