blob: f0d8550773f5ee005ce2cee8b77be1b5419e801d [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"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#else /* Py_REF_DEBUG */
Antoine Pitrouf9d0b122012-12-09 14:28:26 +010041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs, " \
43 "%" PY_FORMAT_SIZE_T "d blocks]\n", \
44 _Py_GetRefTotal(), _Py_GetAllocatedBlocks())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000045#endif
46
47#ifdef __cplusplus
48extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000049#endif
50
Martin v. Löwis790465f2008-04-05 20:41:37 +000051extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000052
Guido van Rossum82598051997-03-05 00:20:32 +000053extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000054
Guido van Rossumb73cc041993-11-01 16:28:59 +000055/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100056static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020057static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000058static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000059static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000060static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000061static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000063static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000064 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000065static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020066static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000067static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000068static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000069static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000070static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +020071extern int _PyUnicode_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000072extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000073extern int _PyLong_Init(void);
74extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020075extern int _PyFaulthandler_Init(void);
76extern void _PyFaulthandler_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 */
Georg Brandl8aa7e992010-12-28 18:30:18 +000085int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000086int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020087int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000088int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000089int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000090int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000091int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000092int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000093int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000094int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000095int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +010096int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000097
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020098PyThreadState *_Py_Finalizing = NULL;
99
Christian Heimes33fe8092008-04-13 13:53:33 +0000100/* PyModule_GetWarningsModule is no longer necessary as of 2.6
101since _warnings is builtin. This API should not be used. */
102PyObject *
103PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000106}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000107
Guido van Rossum25ce5661997-08-02 03:10:38 +0000108static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000109
Thomas Wouters7e474022000-07-16 12:04:32 +0000110/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000111
112int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000113Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000116}
117
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118/* Global initializations. Can be undone by Py_Finalize(). Don't
119 call this twice without an intervening Py_Finalize() call. When
120 initializations fail, a fatal error is issued and the function does
121 not return. On return, the first thread and interpreter state have
122 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000123
Guido van Rossum25ce5661997-08-02 03:10:38 +0000124 Locking: you must hold the interpreter lock while calling this.
125 (If the lock has not yet been initialized, that's equivalent to
126 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000127
Guido van Rossum25ce5661997-08-02 03:10:38 +0000128*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000129
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000130static int
131add_flag(int flag, const char *envs)
132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 int env = atoi(envs);
134 if (flag < env)
135 flag = env;
136 if (flag < 1)
137 flag = 1;
138 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000139}
140
Christian Heimes5833a2f2008-10-30 21:40:04 +0000141static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000142get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000143{
Victor Stinner94908bb2010-08-18 21:23:25 +0000144 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000145 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200146 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000147
Victor Stinner94908bb2010-08-18 21:23:25 +0000148 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (!codec)
150 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000151
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200152 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 Py_CLEAR(codec);
154 if (!name)
155 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000156
Victor Stinner94908bb2010-08-18 21:23:25 +0000157 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100158 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000159 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000160 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000162 if (name_str == NULL) {
163 PyErr_NoMemory();
164 return NULL;
165 }
166 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000167
168error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000170 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000172}
Victor Stinner94908bb2010-08-18 21:23:25 +0000173
Victor Stinner94908bb2010-08-18 21:23:25 +0000174static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200175get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000176{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200177#ifdef MS_WINDOWS
178 char codepage[100];
179 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
180 return get_codec_name(codepage);
181#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000182 char* codeset = nl_langinfo(CODESET);
183 if (!codeset || codeset[0] == '\0') {
184 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
185 return NULL;
186 }
187 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200188#else
189 PyErr_SetNone(PyExc_NotImplementedError);
190 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000191#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200192}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000193
Brett Cannonfd074152012-04-14 14:10:13 -0400194static void
195import_init(PyInterpreterState *interp, PyObject *sysmod)
196{
197 PyObject *importlib;
198 PyObject *impmod;
199 PyObject *sys_modules;
200 PyObject *value;
201
202 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400203 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
204 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
205 }
206 else if (Py_VerboseFlag) {
207 PySys_FormatStderr("import _frozen_importlib # frozen\n");
208 }
209 importlib = PyImport_AddModule("_frozen_importlib");
210 if (importlib == NULL) {
211 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
212 "sys.modules");
213 }
214 interp->importlib = importlib;
215 Py_INCREF(interp->importlib);
216
217 /* Install _importlib as __import__ */
218 impmod = PyInit_imp();
219 if (impmod == NULL) {
220 Py_FatalError("Py_Initialize: can't import imp");
221 }
222 else if (Py_VerboseFlag) {
223 PySys_FormatStderr("import imp # builtin\n");
224 }
225 sys_modules = PyImport_GetModuleDict();
226 if (Py_VerboseFlag) {
227 PySys_FormatStderr("import sys # builtin\n");
228 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400229 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
230 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400231 }
232
Brett Cannone0d88a12012-04-25 20:54:04 -0400233 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400234 if (value == NULL) {
235 PyErr_Print();
236 Py_FatalError("Py_Initialize: importlib install failed");
237 }
238 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400239 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400240
241 _PyImportZip_Init();
242}
243
244
Guido van Rossuma027efa1997-05-05 20:56:21 +0000245void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200246_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 PyInterpreterState *interp;
249 PyThreadState *tstate;
250 PyObject *bimod, *sysmod, *pstderr;
251 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 if (initialized)
255 return;
256 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200257 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000258
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000259#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 /* Set up the LC_CTYPE locale, so we can obtain
261 the locale's charset without having to switch
262 locales. */
263 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000264#endif
265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
267 Py_DebugFlag = add_flag(Py_DebugFlag, p);
268 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
269 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
270 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
271 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
272 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
273 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100274 /* The variable is only tested for existence here; _PyRandom_Init will
275 check its value further. */
276 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
277 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
278
279 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 interp = PyInterpreterState_New();
282 if (interp == NULL)
283 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 tstate = PyThreadState_New(interp);
286 if (tstate == NULL)
287 Py_FatalError("Py_Initialize: can't make first thread");
288 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000289
Victor Stinner6961bd62010-08-17 22:26:51 +0000290#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000291 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
292 destroying the GIL might fail when it is being referenced from
293 another running thread (see issue #9901).
294 Instead we destroy the previously created GIL here, which ensures
295 that we can call Py_Initialize / Py_Finalize multiple times. */
296 _PyEval_FiniThreads();
297
298 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000299 _PyGILState_Init(interp, tstate);
300#endif /* WITH_THREAD */
301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 if (!_PyFrame_Init())
305 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (!_PyLong_Init())
308 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (!PyByteArray_Init())
311 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 interp->modules = PyDict_New();
316 if (interp->modules == NULL)
317 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200320 if (_PyUnicode_Init() < 0)
321 Py_FatalError("Py_Initialize: can't initialize unicode");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 bimod = _PyBuiltin_Init();
324 if (bimod == NULL)
325 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000326 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 interp->builtins = PyModule_GetDict(bimod);
328 if (interp->builtins == NULL)
329 Py_FatalError("Py_Initialize: can't initialize builtins dict");
330 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400333 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 sysmod = _PySys_Init();
336 if (sysmod == NULL)
337 Py_FatalError("Py_Initialize: can't initialize sys");
338 interp->sysdict = PyModule_GetDict(sysmod);
339 if (interp->sysdict == NULL)
340 Py_FatalError("Py_Initialize: can't initialize sys dict");
341 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000342 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 PySys_SetPath(Py_GetPath());
344 PyDict_SetItemString(interp->sysdict, "modules",
345 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 /* Set up a preliminary stderr printer until we have enough
348 infrastructure for the io module in place. */
349 pstderr = PyFile_NewStdPrinter(fileno(stderr));
350 if (pstderr == NULL)
351 Py_FatalError("Py_Initialize: can't set preliminary stderr");
352 PySys_SetObject("stderr", pstderr);
353 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000354 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000359
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000360 /* Initialize _warnings. */
361 _PyWarnings_Init();
362
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200363 if (!install_importlib)
364 return;
365
Brett Cannonfd074152012-04-14 14:10:13 -0400366 import_init(interp, sysmod);
367
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200368 /* initialize the faulthandler module */
369 if (_PyFaulthandler_Init())
370 Py_FatalError("Py_Initialize: can't initialize faulthandler");
371
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000372 _PyTime_Init();
373
Victor Stinner793b5312011-04-27 00:24:21 +0200374 if (initfsencoding(interp) < 0)
375 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 if (install_sigs)
378 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000379
Nick Coghlan85e729e2012-07-15 18:09:52 +1000380 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (initstdio() < 0)
382 Py_FatalError(
383 "Py_Initialize: can't initialize sys standard streams");
384
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000385 /* Initialize warnings. */
386 if (PySys_HasWarnOptions()) {
387 PyObject *warnings_module = PyImport_ImportModule("warnings");
388 if (warnings_module == NULL) {
389 fprintf(stderr, "'import warnings' failed; traceback:\n");
390 PyErr_Print();
391 }
392 Py_XDECREF(warnings_module);
393 }
394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 if (!Py_NoSiteFlag)
396 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000397}
398
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000399void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200400Py_InitializeEx(int install_sigs)
401{
402 _Py_InitializeEx_Private(install_sigs, 1);
403}
404
405void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000406Py_Initialize(void)
407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000409}
410
411
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000412#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000413extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000414#endif
415
Guido van Rossume8432ac2007-07-09 15:04:50 +0000416/* Flush stdout and stderr */
417
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100418static int
419file_is_closed(PyObject *fobj)
420{
421 int r;
422 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
423 if (tmp == NULL) {
424 PyErr_Clear();
425 return 0;
426 }
427 r = PyObject_IsTrue(tmp);
428 Py_DECREF(tmp);
429 if (r < 0)
430 PyErr_Clear();
431 return r > 0;
432}
433
Neal Norwitz2bad9702007-08-27 06:19:22 +0000434static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000435flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 PyObject *fout = PySys_GetObject("stdout");
438 PyObject *ferr = PySys_GetObject("stderr");
439 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200440 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000441
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100442 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200443 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000445 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 else
447 Py_DECREF(tmp);
448 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000449
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100450 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200451 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (tmp == NULL)
453 PyErr_Clear();
454 else
455 Py_DECREF(tmp);
456 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000457}
458
Guido van Rossum25ce5661997-08-02 03:10:38 +0000459/* Undo the effect of Py_Initialize().
460
461 Beware: if multiple interpreter and/or thread states exist, these
462 are not wiped out; only the current thread and interpreter state
463 are deleted. But since everything else is deleted, those other
464 interpreter and thread states should no longer be used.
465
466 (XXX We should do better, e.g. wipe out all interpreters and
467 threads.)
468
469 Locking: as above.
470
471*/
472
473void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000474Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyInterpreterState *interp;
477 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (!initialized)
480 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* The interpreter is still entirely intact at this point, and the
485 * exit funcs may be relying on that. In particular, if some thread
486 * or exit func is still waiting to do an import, the import machinery
487 * expects Py_IsInitialized() to return true. So don't say the
488 * interpreter is uninitialized until after the exit funcs have run.
489 * Note that Threading.py uses an exit func to do a join on all the
490 * threads created thru it, so this also protects pending imports in
491 * the threads created via Threading.
492 */
493 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* Get current thread state and interpreter pointer */
496 tstate = PyThreadState_GET();
497 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000498
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200499 /* Remaining threads (e.g. daemon threads) will automatically exit
500 after taking the GIL (in PyEval_RestoreThread()). */
501 _Py_Finalizing = tstate;
502 initialized = 0;
503
504 /* Flush stdout+stderr */
505 flush_std_files();
506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Disable signal handling */
508 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* Clear type lookup cache */
511 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 /* Collect garbage. This may call finalizers; it's nice to call these
514 * before all modules are destroyed.
515 * XXX If a __del__ or weakref callback is triggered here, and tries to
516 * XXX import a module, bad things can happen, because Python no
517 * XXX longer believes it's initialized.
518 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
519 * XXX is easy to provoke that way. I've also seen, e.g.,
520 * XXX Exception exceptions.ImportError: 'No module named sha'
521 * XXX in <function callback at 0x008F5718> ignored
522 * XXX but I'm unclear on exactly how that one happens. In any case,
523 * XXX I haven't seen a real-life report of either of these.
524 */
525 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000526#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 /* With COUNT_ALLOCS, it helps to run GC multiple times:
528 each collection might release some types from the type
529 list, so they become garbage. */
530 while (PyGC_Collect() > 0)
531 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000532#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000533 /* We run this while most interpreter state is still alive, so that
534 debug information can be printed out */
535 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 /* Destroy all modules */
538 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 /* Flush stdout+stderr (again, in case more was printed) */
541 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100544 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 * XXX This is disabled because it caused too many problems. If
546 * XXX a __del__ or weakref callback triggers here, Python code has
547 * XXX a hard time running, because even the sys module has been
548 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
549 * XXX One symptom is a sequence of information-free messages
550 * XXX coming from threads (if a __del__ or callback is invoked,
551 * XXX other threads can execute too, and any exception they encounter
552 * XXX triggers a comedy of errors as subsystem after subsystem
553 * XXX fails to find what it *expects* to find in sys to help report
554 * XXX the exception and consequent unexpected failures). I've also
555 * XXX seen segfaults then, after adding print statements to the
556 * XXX Python code getting called.
557 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000558#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000560#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
563 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000564
Victor Stinner024e37a2011-03-31 01:31:06 +0200565 /* unload faulthandler module */
566 _PyFaulthandler_Fini();
567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000569#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000571#endif
572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000574
Tim Peters9cf25ce2003-04-17 15:21:01 +0000575#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 /* Display all objects still alive -- this can invoke arbitrary
577 * __repr__ overrides, so requires a mostly-intact interpreter.
578 * Alas, a lot of stuff may still be alive now that will be cleaned
579 * up later.
580 */
581 if (Py_GETENV("PYTHONDUMPREFS"))
582 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000583#endif /* Py_TRACE_REFS */
584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 /* Clear interpreter state */
586 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* Now we decref the exception classes. After this point nothing
589 can raise an exception. That's okay, because each Fini() method
590 below has been checked to make sure no exceptions are ever
591 raised.
592 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000597#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000599#endif /* WITH_THREAD */
600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 /* Delete current thread */
602 PyThreadState_Swap(NULL);
603 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 /* Sundry finalizers */
606 PyMethod_Fini();
607 PyFrame_Fini();
608 PyCFunction_Fini();
609 PyTuple_Fini();
610 PyList_Fini();
611 PySet_Fini();
612 PyBytes_Fini();
613 PyByteArray_Fini();
614 PyLong_Fini();
615 PyFloat_Fini();
616 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100617 PySlice_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 /* Cleanup Unicode implementation */
620 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000623 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 free((char*)Py_FileSystemDefaultEncoding);
625 Py_FileSystemDefaultEncoding = NULL;
626 }
Christian Heimesc8967002007-11-30 10:18:26 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 /* XXX Still allocated:
629 - various static ad-hoc pointers to interned strings
630 - int and float free list blocks
631 - whatever various modules and libraries allocate
632 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000635
Tim Peters269b2a62003-04-17 19:52:29 +0000636#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 /* Display addresses (& refcnts) of all objects still alive.
638 * An address can be used to find the repr of the object, printed
639 * above by _Py_PrintReferences.
640 */
641 if (Py_GETENV("PYTHONDUMPREFS"))
642 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000643#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000644#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400646 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000647#endif
648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000650}
651
652/* Create and initialize a new interpreter and thread, and return the
653 new thread. This requires that Py_Initialize() has been called
654 first.
655
656 Unsuccessful initialization yields a NULL pointer. Note that *no*
657 exception information is available even in this case -- the
658 exception information is held in the thread, and there is no
659 thread.
660
661 Locking: as above.
662
663*/
664
665PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000666Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyInterpreterState *interp;
669 PyThreadState *tstate, *save_tstate;
670 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 if (!initialized)
673 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 interp = PyInterpreterState_New();
676 if (interp == NULL)
677 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 tstate = PyThreadState_New(interp);
680 if (tstate == NULL) {
681 PyInterpreterState_Delete(interp);
682 return NULL;
683 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000684
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000690
Victor Stinner49d3f252010-10-17 01:24:53 +0000691 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (bimod != NULL) {
693 interp->builtins = PyModule_GetDict(bimod);
694 if (interp->builtins == NULL)
695 goto handle_error;
696 Py_INCREF(interp->builtins);
697 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400700 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000701
Victor Stinner49d3f252010-10-17 01:24:53 +0000702 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 if (bimod != NULL && sysmod != NULL) {
704 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 interp->sysdict = PyModule_GetDict(sysmod);
707 if (interp->sysdict == NULL)
708 goto handle_error;
709 Py_INCREF(interp->sysdict);
710 PySys_SetPath(Py_GetPath());
711 PyDict_SetItemString(interp->sysdict, "modules",
712 interp->modules);
713 /* Set up a preliminary stderr printer until we have enough
714 infrastructure for the io module in place. */
715 pstderr = PyFile_NewStdPrinter(fileno(stderr));
716 if (pstderr == NULL)
717 Py_FatalError("Py_Initialize: can't set preliminary stderr");
718 PySys_SetObject("stderr", pstderr);
719 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000720 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200723
Brett Cannonfd074152012-04-14 14:10:13 -0400724 import_init(interp, sysmod);
725
Victor Stinner793b5312011-04-27 00:24:21 +0200726 if (initfsencoding(interp) < 0)
727 goto handle_error;
728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 if (initstdio() < 0)
730 Py_FatalError(
731 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000732 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (!Py_NoSiteFlag)
734 initsite();
735 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 if (!PyErr_Occurred())
738 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000739
Thomas Wouters89f507f2006-12-13 04:49:30 +0000740handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000742
Victor Stinnerc40a3502011-04-27 00:20:27 +0200743 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 PyThreadState_Clear(tstate);
745 PyThreadState_Swap(save_tstate);
746 PyThreadState_Delete(tstate);
747 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000750}
751
752/* Delete an interpreter and its last thread. This requires that the
753 given thread state is current, that the thread has no remaining
754 frames, and that it is its interpreter's only remaining thread.
755 It is a fatal error to violate these constraints.
756
757 (Py_Finalize() doesn't have these constraints -- it zaps
758 everything, regardless.)
759
760 Locking: as above.
761
762*/
763
764void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000765Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (tstate != PyThreadState_GET())
770 Py_FatalError("Py_EndInterpreter: thread is not current");
771 if (tstate->frame != NULL)
772 Py_FatalError("Py_EndInterpreter: thread still has a frame");
773 if (tstate != interp->tstate_head || tstate->next != NULL)
774 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 PyImport_Cleanup();
777 PyInterpreterState_Clear(interp);
778 PyThreadState_Swap(NULL);
779 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000780}
781
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200782#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000783static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200784#else
785static wchar_t *progname = L"python3";
786#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000787
788void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000789Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (pn && *pn)
792 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000793}
794
Martin v. Löwis790465f2008-04-05 20:41:37 +0000795wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000796Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000799}
800
Martin v. Löwis790465f2008-04-05 20:41:37 +0000801static wchar_t *default_home = NULL;
802static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000803
804void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000805Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000808}
809
Martin v. Löwis790465f2008-04-05 20:41:37 +0000810wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000811Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 wchar_t *home = default_home;
814 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
815 char* chome = Py_GETENV("PYTHONHOME");
816 if (chome) {
817 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
818 if (r != (size_t)-1 && r <= PATH_MAX)
819 home = env_home;
820 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 }
823 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000824}
825
Guido van Rossum6135a871995-01-09 17:53:26 +0000826/* Create __main__ module */
827
828static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000829initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 PyObject *m, *d;
832 m = PyImport_AddModule("__main__");
833 if (m == NULL)
834 Py_FatalError("can't create __main__ module");
835 d = PyModule_GetDict(m);
836 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
837 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000838 if (bimod == NULL) {
839 Py_FatalError("Failed to retrieve builtins module");
840 }
841 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
842 Py_FatalError("Failed to initialize __main__.__builtins__");
843 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 Py_DECREF(bimod);
845 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000846 /* Main is a little special - imp.is_builtin("__main__") will return
847 * False, but BuiltinImporter is still the most appropriate initial
848 * setting for its __loader__ attribute. A more suitable value will
849 * be set if __main__ gets further initialized later in the startup
850 * process.
851 */
852 if (PyDict_GetItemString(d, "__loader__") == NULL) {
853 PyObject *loader = PyObject_GetAttrString(interp->importlib,
854 "BuiltinImporter");
855 if (loader == NULL) {
856 Py_FatalError("Failed to retrieve BuiltinImporter");
857 }
858 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
859 Py_FatalError("Failed to initialize __main__.__loader__");
860 }
861 Py_DECREF(loader);
862 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000863}
864
Victor Stinner793b5312011-04-27 00:24:21 +0200865static int
866initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000867{
868 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000869
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200870 if (Py_FileSystemDefaultEncoding == NULL)
871 {
872 Py_FileSystemDefaultEncoding = get_locale_encoding();
873 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000874 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000875
Victor Stinnere4743092010-10-19 00:05:51 +0000876 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200877 interp->fscodec_initialized = 1;
878 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000879 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000880
881 /* the encoding is mbcs, utf-8 or ascii */
882 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
883 if (!codec) {
884 /* Such error can only occurs in critical situations: no more
885 * memory, import a module of the standard library failed,
886 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200887 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000888 }
Victor Stinner793b5312011-04-27 00:24:21 +0200889 Py_DECREF(codec);
890 interp->fscodec_initialized = 1;
891 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000892}
893
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000894/* Import the site module (not into __main__ though) */
895
896static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000897initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 PyObject *m;
900 m = PyImport_ImportModule("site");
901 if (m == NULL) {
902 PyErr_Print();
903 Py_Finalize();
904 exit(1);
905 }
906 else {
907 Py_DECREF(m);
908 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000909}
910
Antoine Pitrou05608432009-01-09 18:53:14 +0000911static PyObject*
912create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 int fd, int write_mode, char* name,
914 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
917 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000918 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 PyObject *line_buffering;
920 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200921 _Py_IDENTIFIER(open);
922 _Py_IDENTIFIER(isatty);
923 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200924 _Py_IDENTIFIER(name);
925 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 /* stdin is always opened in buffered mode, first because it shouldn't
928 make a difference in common use cases, second because TextIOWrapper
929 depends on the presence of a read1() method which only exists on
930 buffered streams.
931 */
932 if (Py_UnbufferedStdioFlag && write_mode)
933 buffering = 0;
934 else
935 buffering = -1;
936 if (write_mode)
937 mode = "wb";
938 else
939 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200940 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
941 fd, mode, buffering,
942 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 if (buf == NULL)
944 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200947 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200948 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (raw == NULL)
950 goto error;
951 }
952 else {
953 raw = buf;
954 Py_INCREF(raw);
955 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200958 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200960 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 if (res == NULL)
962 goto error;
963 isatty = PyObject_IsTrue(res);
964 Py_DECREF(res);
965 if (isatty == -1)
966 goto error;
967 if (isatty || Py_UnbufferedStdioFlag)
968 line_buffering = Py_True;
969 else
970 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 Py_CLEAR(raw);
973 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000974
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000975#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +0200976 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
977 newlines to "\n".
978 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
979 newline = NULL;
980#else
981 /* sys.stdin: split lines at "\n".
982 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
983 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000984#endif
985
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200986 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
987 buf, encoding, errors,
988 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 Py_CLEAR(buf);
990 if (stream == NULL)
991 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (write_mode)
994 mode = "w";
995 else
996 mode = "r";
997 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200998 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 goto error;
1000 Py_CLEAR(text);
1001 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001002
1003error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 Py_XDECREF(buf);
1005 Py_XDECREF(stream);
1006 Py_XDECREF(text);
1007 Py_XDECREF(raw);
1008 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001009}
1010
Antoine Pitrou11942a52011-11-28 19:08:36 +01001011static int
1012is_valid_fd(int fd)
1013{
1014 int dummy_fd;
1015 if (fd < 0 || !_PyVerify_fd(fd))
1016 return 0;
1017 dummy_fd = dup(fd);
1018 if (dummy_fd < 0)
1019 return 0;
1020 close(dummy_fd);
1021 return 1;
1022}
1023
Georg Brandl1a3284e2007-12-02 09:40:06 +00001024/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001025static int
1026initstdio(void)
1027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyObject *iomod = NULL, *wrapper;
1029 PyObject *bimod = NULL;
1030 PyObject *m;
1031 PyObject *std = NULL;
1032 int status = 0, fd;
1033 PyObject * encoding_attr;
1034 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 /* Hack to avoid a nasty recursion issue when Python is invoked
1037 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1038 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1039 goto error;
1040 }
1041 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1044 goto error;
1045 }
1046 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 if (!(bimod = PyImport_ImportModule("builtins"))) {
1049 goto error;
1050 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 if (!(iomod = PyImport_ImportModule("io"))) {
1053 goto error;
1054 }
1055 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1056 goto error;
1057 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 /* Set builtins.open */
1060 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001061 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 goto error;
1063 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001064 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 encoding = Py_GETENV("PYTHONIOENCODING");
1067 errors = NULL;
1068 if (encoding) {
1069 encoding = strdup(encoding);
1070 errors = strchr(encoding, ':');
1071 if (errors) {
1072 *errors = '\0';
1073 errors++;
1074 }
1075 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 /* Set sys.stdin */
1078 fd = fileno(stdin);
1079 /* Under some conditions stdin, stdout and stderr may not be connected
1080 * and fileno() may point to an invalid file descriptor. For example
1081 * GUI apps don't have valid standard streams by default.
1082 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001083 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 std = Py_None;
1085 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 }
1087 else {
1088 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1089 if (std == NULL)
1090 goto error;
1091 } /* if (fd < 0) */
1092 PySys_SetObject("__stdin__", std);
1093 PySys_SetObject("stdin", std);
1094 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 /* Set sys.stdout */
1097 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001098 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 std = Py_None;
1100 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 }
1102 else {
1103 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1104 if (std == NULL)
1105 goto error;
1106 } /* if (fd < 0) */
1107 PySys_SetObject("__stdout__", std);
1108 PySys_SetObject("stdout", std);
1109 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001110
Guido van Rossum98297ee2007-11-06 21:34:58 +00001111#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 /* Set sys.stderr, replaces the preliminary stderr */
1113 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001114 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 std = Py_None;
1116 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 }
1118 else {
1119 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1120 if (std == NULL)
1121 goto error;
1122 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 /* Same as hack above, pre-import stderr's codec to avoid recursion
1125 when import.c tries to write to stderr in verbose mode. */
1126 encoding_attr = PyObject_GetAttrString(std, "encoding");
1127 if (encoding_attr != NULL) {
1128 const char * encoding;
1129 encoding = _PyUnicode_AsString(encoding_attr);
1130 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001131 PyObject *codec_info = _PyCodec_Lookup(encoding);
1132 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001134 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 }
1136 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 PySys_SetObject("__stderr__", std);
1139 PySys_SetObject("stderr", std);
1140 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001141#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001144 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 status = -1;
1146 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 if (encoding)
1149 free(encoding);
1150 Py_XDECREF(bimod);
1151 Py_XDECREF(iomod);
1152 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001153}
1154
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001155/* Parse input from a file and execute it */
1156
1157int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001158PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (filename == NULL)
1162 filename = "???";
1163 if (Py_FdIsInteractive(fp, filename)) {
1164 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1165 if (closeit)
1166 fclose(fp);
1167 return err;
1168 }
1169 else
1170 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001171}
1172
1173int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001174PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 PyObject *v;
1177 int ret;
1178 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 if (flags == NULL) {
1181 flags = &local_flags;
1182 local_flags.cf_flags = 0;
1183 }
1184 v = PySys_GetObject("ps1");
1185 if (v == NULL) {
1186 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1187 Py_XDECREF(v);
1188 }
1189 v = PySys_GetObject("ps2");
1190 if (v == NULL) {
1191 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1192 Py_XDECREF(v);
1193 }
1194 for (;;) {
1195 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1196 PRINT_TOTAL_REFS();
1197 if (ret == E_EOF)
1198 return 0;
1199 /*
1200 if (ret == E_NOMEM)
1201 return -1;
1202 */
1203 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001204}
1205
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001206/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001207static int PARSER_FLAGS(PyCompilerFlags *flags)
1208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 int parser_flags = 0;
1210 if (!flags)
1211 return 0;
1212 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1213 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1214 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1215 parser_flags |= PyPARSE_IGNORE_COOKIE;
1216 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1217 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1218 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001219}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001220
Thomas Wouters89f507f2006-12-13 04:49:30 +00001221#if 0
1222/* Keep an example of flags with future keyword support. */
1223#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1225 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1226 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1227 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001228#endif
1229
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001230int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001231PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 PyObject *m, *d, *v, *w, *oenc = NULL;
1234 mod_ty mod;
1235 PyArena *arena;
1236 char *ps1 = "", *ps2 = "", *enc = NULL;
1237 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001238 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 if (fp == stdin) {
1241 /* Fetch encoding from sys.stdin */
1242 v = PySys_GetObject("stdin");
1243 if (v == NULL || v == Py_None)
1244 return -1;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001245 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 if (!oenc)
1247 return -1;
1248 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001249 if (enc == NULL)
1250 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 }
1252 v = PySys_GetObject("ps1");
1253 if (v != NULL) {
1254 v = PyObject_Str(v);
1255 if (v == NULL)
1256 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001257 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001258 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001259 if (ps1 == NULL) {
1260 PyErr_Clear();
1261 ps1 = "";
1262 }
1263 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 }
1265 w = PySys_GetObject("ps2");
1266 if (w != NULL) {
1267 w = PyObject_Str(w);
1268 if (w == NULL)
1269 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001270 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001272 if (ps2 == NULL) {
1273 PyErr_Clear();
1274 ps2 = "";
1275 }
1276 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 }
1278 arena = PyArena_New();
1279 if (arena == NULL) {
1280 Py_XDECREF(v);
1281 Py_XDECREF(w);
1282 Py_XDECREF(oenc);
1283 return -1;
1284 }
1285 mod = PyParser_ASTFromFile(fp, filename, enc,
1286 Py_single_input, ps1, ps2,
1287 flags, &errcode, arena);
1288 Py_XDECREF(v);
1289 Py_XDECREF(w);
1290 Py_XDECREF(oenc);
1291 if (mod == NULL) {
1292 PyArena_Free(arena);
1293 if (errcode == E_EOF) {
1294 PyErr_Clear();
1295 return E_EOF;
1296 }
1297 PyErr_Print();
1298 return -1;
1299 }
1300 m = PyImport_AddModule("__main__");
1301 if (m == NULL) {
1302 PyArena_Free(arena);
1303 return -1;
1304 }
1305 d = PyModule_GetDict(m);
1306 v = run_mod(mod, filename, d, d, flags, arena);
1307 PyArena_Free(arena);
1308 flush_io();
1309 if (v == NULL) {
1310 PyErr_Print();
1311 return -1;
1312 }
1313 Py_DECREF(v);
1314 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001315}
1316
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001317/* Check whether a file maybe a pyc file: Look at the extension,
1318 the file type, and, if we may close it, at the first few bytes. */
1319
1320static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001321maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1324 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 /* Only look into the file if we are allowed to close it, since
1327 it then should also be seekable. */
1328 if (closeit) {
1329 /* Read only two bytes of the magic. If the file was opened in
1330 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1331 be read as they are on disk. */
1332 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1333 unsigned char buf[2];
1334 /* Mess: In case of -x, the stream is NOT at its start now,
1335 and ungetc() was used to push back the first newline,
1336 which makes the current stream position formally undefined,
1337 and a x-platform nightmare.
1338 Unfortunately, we have no direct way to know whether -x
1339 was specified. So we use a terrible hack: if the current
1340 stream position is not 0, we assume -x was specified, and
1341 give up. Bug 132850 on SourceForge spells out the
1342 hopelessness of trying anything else (fseek and ftell
1343 don't work predictably x-platform for text-mode files).
1344 */
1345 int ispyc = 0;
1346 if (ftell(fp) == 0) {
1347 if (fread(buf, 1, 2, fp) == 2 &&
1348 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1349 ispyc = 1;
1350 rewind(fp);
1351 }
1352 return ispyc;
1353 }
1354 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001355}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001356
Guido van Rossum0df002c2000-08-27 19:21:52 +00001357int
Nick Coghlanceda83c2012-07-15 23:18:08 +10001358static set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001359{
1360 PyInterpreterState *interp;
1361 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001362 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001363 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001364
1365 filename_obj = PyUnicode_DecodeFSDefault(filename);
1366 if (filename_obj == NULL)
1367 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001368 /* Get current thread state and interpreter pointer */
1369 tstate = PyThreadState_GET();
1370 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001371 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1372 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001373 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001374 return -1;
1375 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001376 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001377 Py_DECREF(loader_type);
1378 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001379 return -1;
1380 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001381 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1382 result = -1;
1383 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001384 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001385 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001386}
1387
1388int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001389PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 PyObject *m, *d, *v;
1393 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001394 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001395 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 m = PyImport_AddModule("__main__");
1398 if (m == NULL)
1399 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001400 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 d = PyModule_GetDict(m);
1402 if (PyDict_GetItemString(d, "__file__") == NULL) {
1403 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001404 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001406 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1408 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001409 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001411 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1412 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001413 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001414 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 set_file_name = 1;
1416 Py_DECREF(f);
1417 }
1418 len = strlen(filename);
1419 ext = filename + len - (len > 4 ? 4 : 0);
1420 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001421 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /* Try to run a pyc file. First, re-open in binary */
1423 if (closeit)
1424 fclose(fp);
Christian Heimes04ac4c12012-09-11 15:47:28 +02001425 if ((pyc_fp = fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 goto done;
1428 }
1429 /* Turn on optimization if a .pyo file is given */
1430 if (strcmp(ext, ".pyo") == 0)
1431 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001432
1433 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1434 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1435 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001436 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001437 goto done;
1438 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001439 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1440 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001442 /* When running from stdin, leave __main__.__loader__ alone */
1443 if (strcmp(filename, "<stdin>") != 0 &&
1444 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1445 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1446 ret = -1;
1447 goto done;
1448 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1450 closeit, flags);
1451 }
1452 flush_io();
1453 if (v == NULL) {
1454 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 goto done;
1456 }
1457 Py_DECREF(v);
1458 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001459 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1461 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001462 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001464}
1465
1466int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001467PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 PyObject *m, *d, *v;
1470 m = PyImport_AddModule("__main__");
1471 if (m == NULL)
1472 return -1;
1473 d = PyModule_GetDict(m);
1474 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1475 if (v == NULL) {
1476 PyErr_Print();
1477 return -1;
1478 }
1479 Py_DECREF(v);
1480 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001481}
1482
Barry Warsaw035574d1997-08-29 22:07:17 +00001483static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001484parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 long hold;
1488 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001489 _Py_IDENTIFIER(msg);
1490 _Py_IDENTIFIER(filename);
1491 _Py_IDENTIFIER(lineno);
1492 _Py_IDENTIFIER(offset);
1493 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001494
Benjamin Peterson80d50422012-04-03 00:30:38 -04001495 *message = NULL;
1496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001498 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001499 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001501
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001502 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001503 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001505 if (v == Py_None) {
1506 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001508 }
1509 else {
1510 *filename = _PyUnicode_AsString(v);
1511 Py_DECREF(v);
1512 if (!*filename)
1513 goto finally;
1514 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001515
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001516 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001517 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 goto finally;
1519 hold = PyLong_AsLong(v);
1520 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 if (hold < 0 && PyErr_Occurred())
1522 goto finally;
1523 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001524
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001525 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001526 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 goto finally;
1528 if (v == Py_None) {
1529 *offset = -1;
1530 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 } else {
1532 hold = PyLong_AsLong(v);
1533 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (hold < 0 && PyErr_Occurred())
1535 goto finally;
1536 *offset = (int)hold;
1537 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001538
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001539 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001540 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001542 if (v == Py_None) {
1543 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001545 }
1546 else {
1547 *text = _PyUnicode_AsString(v);
1548 Py_DECREF(v);
1549 if (!*text)
1550 goto finally;
1551 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001553
1554finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001555 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001557}
1558
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001559void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001560PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001563}
1564
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001565static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001566print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 char *nl;
1569 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001570 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1571 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 for (;;) {
1573 nl = strchr(text, '\n');
1574 if (nl == NULL || nl-text >= offset)
1575 break;
1576 offset -= (int)(nl+1-text);
1577 text = nl+1;
1578 }
1579 while (*text == ' ' || *text == '\t') {
1580 text++;
1581 offset--;
1582 }
1583 }
1584 PyFile_WriteString(" ", f);
1585 PyFile_WriteString(text, f);
1586 if (*text == '\0' || text[strlen(text)-1] != '\n')
1587 PyFile_WriteString("\n", f);
1588 if (offset == -1)
1589 return;
1590 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001591 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001594}
1595
Guido van Rossum66e8e862001-03-23 17:54:43 +00001596static void
1597handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 PyObject *exception, *value, *tb;
1600 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 if (Py_InspectFlag)
1603 /* Don't exit if -i flag was given. This flag is set to 0
1604 * when entering interactive mode for inspecting. */
1605 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 PyErr_Fetch(&exception, &value, &tb);
1608 fflush(stdout);
1609 if (value == NULL || value == Py_None)
1610 goto done;
1611 if (PyExceptionInstance_Check(value)) {
1612 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001613 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001614 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 if (code) {
1616 Py_DECREF(value);
1617 value = code;
1618 if (value == Py_None)
1619 goto done;
1620 }
1621 /* If we failed to dig out the 'code' attribute,
1622 just let the else clause below print the error. */
1623 }
1624 if (PyLong_Check(value))
1625 exitcode = (int)PyLong_AsLong(value);
1626 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001627 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001628 if (sys_stderr != NULL && sys_stderr != Py_None) {
1629 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1630 } else {
1631 PyObject_Print(value, stderr, Py_PRINT_RAW);
1632 fflush(stderr);
1633 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 PySys_WriteStderr("\n");
1635 exitcode = 1;
1636 }
Tim Peterscf615b52003-04-19 18:47:02 +00001637 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 /* Restore and clear the exception info, in order to properly decref
1639 * the exception, value, and traceback. If we just exit instead,
1640 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1641 * some finalizers from running.
1642 */
1643 PyErr_Restore(exception, value, tb);
1644 PyErr_Clear();
1645 Py_Exit(exitcode);
1646 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001647}
1648
1649void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001650PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1655 handle_system_exit();
1656 }
1657 PyErr_Fetch(&exception, &v, &tb);
1658 if (exception == NULL)
1659 return;
1660 PyErr_NormalizeException(&exception, &v, &tb);
1661 if (tb == NULL) {
1662 tb = Py_None;
1663 Py_INCREF(tb);
1664 }
1665 PyException_SetTraceback(v, tb);
1666 if (exception == NULL)
1667 return;
1668 /* Now we know v != NULL too */
1669 if (set_sys_last_vars) {
1670 PySys_SetObject("last_type", exception);
1671 PySys_SetObject("last_value", v);
1672 PySys_SetObject("last_traceback", tb);
1673 }
1674 hook = PySys_GetObject("excepthook");
1675 if (hook) {
1676 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1677 PyObject *result = PyEval_CallObject(hook, args);
1678 if (result == NULL) {
1679 PyObject *exception2, *v2, *tb2;
1680 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1681 handle_system_exit();
1682 }
1683 PyErr_Fetch(&exception2, &v2, &tb2);
1684 PyErr_NormalizeException(&exception2, &v2, &tb2);
1685 /* It should not be possible for exception2 or v2
1686 to be NULL. However PyErr_Display() can't
1687 tolerate NULLs, so just be safe. */
1688 if (exception2 == NULL) {
1689 exception2 = Py_None;
1690 Py_INCREF(exception2);
1691 }
1692 if (v2 == NULL) {
1693 v2 = Py_None;
1694 Py_INCREF(v2);
1695 }
1696 fflush(stdout);
1697 PySys_WriteStderr("Error in sys.excepthook:\n");
1698 PyErr_Display(exception2, v2, tb2);
1699 PySys_WriteStderr("\nOriginal exception was:\n");
1700 PyErr_Display(exception, v, tb);
1701 Py_DECREF(exception2);
1702 Py_DECREF(v2);
1703 Py_XDECREF(tb2);
1704 }
1705 Py_XDECREF(result);
1706 Py_XDECREF(args);
1707 } else {
1708 PySys_WriteStderr("sys.excepthook is missing\n");
1709 PyErr_Display(exception, v, tb);
1710 }
1711 Py_XDECREF(exception);
1712 Py_XDECREF(v);
1713 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001714}
1715
Benjamin Petersone6528212008-07-15 15:32:09 +00001716static void
1717print_exception(PyObject *f, PyObject *value)
1718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 int err = 0;
1720 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001721 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 if (!PyExceptionInstance_Check(value)) {
1724 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1725 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1726 PyFile_WriteString(" found\n", f);
1727 return;
1728 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 Py_INCREF(value);
1731 fflush(stdout);
1732 type = (PyObject *) Py_TYPE(value);
1733 tb = PyException_GetTraceback(value);
1734 if (tb && tb != Py_None)
1735 err = PyTraceBack_Print(tb, f);
1736 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001737 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 {
1739 PyObject *message;
1740 const char *filename, *text;
1741 int lineno, offset;
1742 if (!parse_syntax_error(value, &message, &filename,
1743 &lineno, &offset, &text))
1744 PyErr_Clear();
1745 else {
1746 char buf[10];
1747 PyFile_WriteString(" File \"", f);
1748 if (filename == NULL)
1749 PyFile_WriteString("<string>", f);
1750 else
1751 PyFile_WriteString(filename, f);
1752 PyFile_WriteString("\", line ", f);
1753 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1754 PyFile_WriteString(buf, f);
1755 PyFile_WriteString("\n", f);
1756 if (text != NULL)
1757 print_error_text(f, offset, text);
1758 Py_DECREF(value);
1759 value = message;
1760 /* Can't be bothered to check all those
1761 PyFile_WriteString() calls */
1762 if (PyErr_Occurred())
1763 err = -1;
1764 }
1765 }
1766 if (err) {
1767 /* Don't do anything else */
1768 }
1769 else {
1770 PyObject* moduleName;
1771 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001772 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 assert(PyExceptionClass_Check(type));
1774 className = PyExceptionClass_Name(type);
1775 if (className != NULL) {
1776 char *dot = strrchr(className, '.');
1777 if (dot != NULL)
1778 className = dot+1;
1779 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001780
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001781 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1783 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001784 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 err = PyFile_WriteString("<unknown>", f);
1786 }
1787 else {
1788 char* modstr = _PyUnicode_AsString(moduleName);
1789 if (modstr && strcmp(modstr, "builtins"))
1790 {
1791 err = PyFile_WriteString(modstr, f);
1792 err += PyFile_WriteString(".", f);
1793 }
1794 Py_DECREF(moduleName);
1795 }
1796 if (err == 0) {
1797 if (className == NULL)
1798 err = PyFile_WriteString("<unknown>", f);
1799 else
1800 err = PyFile_WriteString(className, f);
1801 }
1802 }
1803 if (err == 0 && (value != Py_None)) {
1804 PyObject *s = PyObject_Str(value);
1805 /* only print colon if the str() of the
1806 object is not the empty string
1807 */
1808 if (s == NULL)
1809 err = -1;
1810 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001811 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 err = PyFile_WriteString(": ", f);
1813 if (err == 0)
1814 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1815 Py_XDECREF(s);
1816 }
1817 /* try to write a newline in any case */
1818 err += PyFile_WriteString("\n", f);
1819 Py_XDECREF(tb);
1820 Py_DECREF(value);
1821 /* If an error happened here, don't show it.
1822 XXX This is wrong, but too many callers rely on this behavior. */
1823 if (err != 0)
1824 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001825}
1826
1827static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 "\nThe above exception was the direct cause "
1829 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001830
1831static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 "\nDuring handling of the above exception, "
1833 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001834
1835static void
1836print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 int err = 0, res;
1839 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 if (seen != NULL) {
1842 /* Exception chaining */
1843 if (PySet_Add(seen, value) == -1)
1844 PyErr_Clear();
1845 else if (PyExceptionInstance_Check(value)) {
1846 cause = PyException_GetCause(value);
1847 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001848 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 res = PySet_Contains(seen, cause);
1850 if (res == -1)
1851 PyErr_Clear();
1852 if (res == 0) {
1853 print_exception_recursive(
1854 f, cause, seen);
1855 err |= PyFile_WriteString(
1856 cause_message, f);
1857 }
1858 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001859 else if (context &&
1860 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 res = PySet_Contains(seen, context);
1862 if (res == -1)
1863 PyErr_Clear();
1864 if (res == 0) {
1865 print_exception_recursive(
1866 f, context, seen);
1867 err |= PyFile_WriteString(
1868 context_message, f);
1869 }
1870 }
1871 Py_XDECREF(context);
1872 Py_XDECREF(cause);
1873 }
1874 }
1875 print_exception(f, value);
1876 if (err != 0)
1877 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001878}
1879
Thomas Wouters477c8d52006-05-27 19:21:47 +00001880void
1881PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 PyObject *seen;
1884 PyObject *f = PySys_GetObject("stderr");
1885 if (f == Py_None) {
1886 /* pass */
1887 }
1888 else if (f == NULL) {
1889 _PyObject_Dump(value);
1890 fprintf(stderr, "lost sys.stderr\n");
1891 }
1892 else {
1893 /* We choose to ignore seen being possibly NULL, and report
1894 at least the main exception (it could be a MemoryError).
1895 */
1896 seen = PySet_New(NULL);
1897 if (seen == NULL)
1898 PyErr_Clear();
1899 print_exception_recursive(f, value, seen);
1900 Py_XDECREF(seen);
1901 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001902}
1903
Guido van Rossum82598051997-03-05 00:20:32 +00001904PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001905PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 PyObject *ret = NULL;
1909 mod_ty mod;
1910 PyArena *arena = PyArena_New();
1911 if (arena == NULL)
1912 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1915 if (mod != NULL)
1916 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1917 PyArena_Free(arena);
1918 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001919}
1920
1921PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001922PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 PyObject *ret;
1926 mod_ty mod;
1927 PyArena *arena = PyArena_New();
1928 if (arena == NULL)
1929 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1932 flags, NULL, arena);
1933 if (closeit)
1934 fclose(fp);
1935 if (mod == NULL) {
1936 PyArena_Free(arena);
1937 return NULL;
1938 }
1939 ret = run_mod(mod, filename, globals, locals, flags, arena);
1940 PyArena_Free(arena);
1941 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001942}
1943
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001944static void
1945flush_io(void)
1946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 PyObject *f, *r;
1948 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001949 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 /* Save the current exception */
1952 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 f = PySys_GetObject("stderr");
1955 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001956 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 if (r)
1958 Py_DECREF(r);
1959 else
1960 PyErr_Clear();
1961 }
1962 f = PySys_GetObject("stdout");
1963 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001964 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 if (r)
1966 Py_DECREF(r);
1967 else
1968 PyErr_Clear();
1969 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001972}
1973
Guido van Rossum82598051997-03-05 00:20:32 +00001974static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001975run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 PyCodeObject *co;
1979 PyObject *v;
1980 co = PyAST_Compile(mod, filename, flags, arena);
1981 if (co == NULL)
1982 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001983 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 Py_DECREF(co);
1985 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001986}
1987
Guido van Rossum82598051997-03-05 00:20:32 +00001988static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001989run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyCodeObject *co;
1993 PyObject *v;
1994 long magic;
1995 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 magic = PyMarshal_ReadLongFromFile(fp);
1998 if (magic != PyImport_GetMagicNumber()) {
1999 PyErr_SetString(PyExc_RuntimeError,
2000 "Bad magic number in .pyc file");
2001 return NULL;
2002 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002003 /* Skip mtime and size */
2004 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 (void) PyMarshal_ReadLongFromFile(fp);
2006 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 if (v == NULL || !PyCode_Check(v)) {
2008 Py_XDECREF(v);
2009 PyErr_SetString(PyExc_RuntimeError,
2010 "Bad code object in .pyc file");
2011 return NULL;
2012 }
2013 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002014 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 if (v && flags)
2016 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2017 Py_DECREF(co);
2018 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002019}
2020
Guido van Rossum82598051997-03-05 00:20:32 +00002021PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00002022Py_CompileStringExFlags(const char *str, const char *filename, int start,
2023 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 PyCodeObject *co;
2026 mod_ty mod;
2027 PyArena *arena = PyArena_New();
2028 if (arena == NULL)
2029 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
2032 if (mod == NULL) {
2033 PyArena_Free(arena);
2034 return NULL;
2035 }
2036 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2037 PyObject *result = PyAST_mod2obj(mod);
2038 PyArena_Free(arena);
2039 return result;
2040 }
Georg Brandl8334fd92010-12-04 10:26:46 +00002041 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 PyArena_Free(arena);
2043 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002044}
2045
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002046/* For use in Py_LIMITED_API */
2047#undef Py_CompileString
2048PyObject *
2049PyCompileString(const char *str, const char *filename, int start)
2050{
2051 return Py_CompileStringFlags(str, filename, start, NULL);
2052}
2053
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002054struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002055Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 struct symtable *st;
2058 mod_ty mod;
2059 PyCompilerFlags flags;
2060 PyArena *arena = PyArena_New();
2061 if (arena == NULL)
2062 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 flags.cf_flags = 0;
2065 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
2066 if (mod == NULL) {
2067 PyArena_Free(arena);
2068 return NULL;
2069 }
2070 st = PySymtable_Build(mod, filename, 0);
2071 PyArena_Free(arena);
2072 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002073}
2074
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002075/* Preferred access to parser is through AST. */
2076mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002077PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 mod_ty mod;
2081 PyCompilerFlags localflags;
2082 perrdetail err;
2083 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
2086 &_PyParser_Grammar, start, &err,
2087 &iflags);
2088 if (flags == NULL) {
2089 localflags.cf_flags = 0;
2090 flags = &localflags;
2091 }
2092 if (n) {
2093 flags->cf_flags |= iflags & PyCF_MASK;
2094 mod = PyAST_FromNode(n, flags, filename, arena);
2095 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 }
2097 else {
2098 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002099 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002101 err_free(&err);
2102 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002103}
2104
2105mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00002106PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 int start, char *ps1,
2108 char *ps2, PyCompilerFlags *flags, int *errcode,
2109 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 mod_ty mod;
2112 PyCompilerFlags localflags;
2113 perrdetail err;
2114 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
2117 &_PyParser_Grammar,
2118 start, ps1, ps2, &err, &iflags);
2119 if (flags == NULL) {
2120 localflags.cf_flags = 0;
2121 flags = &localflags;
2122 }
2123 if (n) {
2124 flags->cf_flags |= iflags & PyCF_MASK;
2125 mod = PyAST_FromNode(n, flags, filename, arena);
2126 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 }
2128 else {
2129 err_input(&err);
2130 if (errcode)
2131 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002132 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002134 err_free(&err);
2135 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002136}
2137
Guido van Rossuma110aa61994-08-29 12:50:44 +00002138/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002139
Guido van Rossuma110aa61994-08-29 12:50:44 +00002140node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002141PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 perrdetail err;
2144 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2145 &_PyParser_Grammar,
2146 start, NULL, NULL, &err, flags);
2147 if (n == NULL)
2148 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002149 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002152}
2153
Guido van Rossuma110aa61994-08-29 12:50:44 +00002154/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002155
Guido van Rossuma110aa61994-08-29 12:50:44 +00002156node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002157PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 perrdetail err;
2160 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2161 start, &err, flags);
2162 if (n == NULL)
2163 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002164 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002166}
2167
2168node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002169PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 perrdetail err;
2173 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2174 &_PyParser_Grammar, start, &err, flags);
2175 if (n == NULL)
2176 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002177 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002179}
2180
2181node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002182PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002185}
2186
Guido van Rossum66ebd912003-04-17 16:02:26 +00002187/* May want to move a more generalized form of this to parsetok.c or
2188 even parser modules. */
2189
2190void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002191PyParser_ClearError(perrdetail *err)
2192{
2193 err_free(err);
2194}
2195
2196void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002197PyParser_SetError(perrdetail *err)
2198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002200}
2201
Victor Stinner7f2fee32011-04-05 00:39:01 +02002202static void
2203err_free(perrdetail *err)
2204{
2205 Py_CLEAR(err->filename);
2206}
2207
Guido van Rossuma110aa61994-08-29 12:50:44 +00002208/* Set the error appropriate to the given input error code (see errcode.h) */
2209
2210static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002211err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 PyObject *v, *w, *errtype, *errtext;
2214 PyObject *msg_obj = NULL;
2215 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 errtype = PyExc_SyntaxError;
2218 switch (err->error) {
2219 case E_ERROR:
2220 return;
2221 case E_SYNTAX:
2222 errtype = PyExc_IndentationError;
2223 if (err->expected == INDENT)
2224 msg = "expected an indented block";
2225 else if (err->token == INDENT)
2226 msg = "unexpected indent";
2227 else if (err->token == DEDENT)
2228 msg = "unexpected unindent";
2229 else {
2230 errtype = PyExc_SyntaxError;
2231 msg = "invalid syntax";
2232 }
2233 break;
2234 case E_TOKEN:
2235 msg = "invalid token";
2236 break;
2237 case E_EOFS:
2238 msg = "EOF while scanning triple-quoted string literal";
2239 break;
2240 case E_EOLS:
2241 msg = "EOL while scanning string literal";
2242 break;
2243 case E_INTR:
2244 if (!PyErr_Occurred())
2245 PyErr_SetNone(PyExc_KeyboardInterrupt);
2246 goto cleanup;
2247 case E_NOMEM:
2248 PyErr_NoMemory();
2249 goto cleanup;
2250 case E_EOF:
2251 msg = "unexpected EOF while parsing";
2252 break;
2253 case E_TABSPACE:
2254 errtype = PyExc_TabError;
2255 msg = "inconsistent use of tabs and spaces in indentation";
2256 break;
2257 case E_OVERFLOW:
2258 msg = "expression too long";
2259 break;
2260 case E_DEDENT:
2261 errtype = PyExc_IndentationError;
2262 msg = "unindent does not match any outer indentation level";
2263 break;
2264 case E_TOODEEP:
2265 errtype = PyExc_IndentationError;
2266 msg = "too many levels of indentation";
2267 break;
2268 case E_DECODE: {
2269 PyObject *type, *value, *tb;
2270 PyErr_Fetch(&type, &value, &tb);
2271 msg = "unknown decode error";
2272 if (value != NULL)
2273 msg_obj = PyObject_Str(value);
2274 Py_XDECREF(type);
2275 Py_XDECREF(value);
2276 Py_XDECREF(tb);
2277 break;
2278 }
2279 case E_LINECONT:
2280 msg = "unexpected character after line continuation character";
2281 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 case E_IDENTIFIER:
2284 msg = "invalid character in identifier";
2285 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002286 case E_BADSINGLE:
2287 msg = "multiple statements found while compiling a single statement";
2288 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 default:
2290 fprintf(stderr, "error=%d\n", err->error);
2291 msg = "unknown parsing error";
2292 break;
2293 }
2294 /* err->text may not be UTF-8 in case of decoding errors.
2295 Explicitly convert to an object. */
2296 if (!err->text) {
2297 errtext = Py_None;
2298 Py_INCREF(Py_None);
2299 } else {
2300 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2301 "replace");
2302 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002303 v = Py_BuildValue("(OiiN)", err->filename,
2304 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 if (v != NULL) {
2306 if (msg_obj)
2307 w = Py_BuildValue("(OO)", msg_obj, v);
2308 else
2309 w = Py_BuildValue("(sO)", msg, v);
2310 } else
2311 w = NULL;
2312 Py_XDECREF(v);
2313 PyErr_SetObject(errtype, w);
2314 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002315cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 Py_XDECREF(msg_obj);
2317 if (err->text != NULL) {
2318 PyObject_FREE(err->text);
2319 err->text = NULL;
2320 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002321}
2322
2323/* Print fatal error message and abort */
2324
2325void
Tim Peters7c321a82002-07-09 02:57:01 +00002326Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002327{
Victor Stinner024e37a2011-03-31 01:31:06 +02002328 const int fd = fileno(stderr);
2329 PyThreadState *tstate;
2330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 fprintf(stderr, "Fatal Python error: %s\n", msg);
2332 fflush(stderr); /* it helps in Windows debug build */
2333 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002334 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002336 else {
2337 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2338 if (tstate != NULL) {
2339 fputc('\n', stderr);
2340 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002341 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002342 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002343 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002344 }
2345
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002346#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 {
2348 size_t len = strlen(msg);
2349 WCHAR* buffer;
2350 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 /* Convert the message to wchar_t. This uses a simple one-to-one
2353 conversion, assuming that the this error message actually uses ASCII
2354 only. If this ceases to be true, we will have to convert. */
2355 buffer = alloca( (len+1) * (sizeof *buffer));
2356 for( i=0; i<=len; ++i)
2357 buffer[i] = msg[i];
2358 OutputDebugStringW(L"Fatal Python error: ");
2359 OutputDebugStringW(buffer);
2360 OutputDebugStringW(L"\n");
2361 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002362#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002364#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002365#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002367}
2368
2369/* Clean up and exit */
2370
Guido van Rossuma110aa61994-08-29 12:50:44 +00002371#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002372#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002373#endif
2374
Collin Winter670e6922007-03-21 02:57:17 +00002375static void (*pyexitfunc)(void) = NULL;
2376/* For the atexit module. */
2377void _Py_PyAtExit(void (*func)(void))
2378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002380}
2381
2382static void
2383call_py_exitfuncs(void)
2384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 if (pyexitfunc == NULL)
2386 return;
Collin Winter670e6922007-03-21 02:57:17 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 (*pyexitfunc)();
2389 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002390}
2391
Antoine Pitrou011bd622009-10-20 21:52:47 +00002392/* Wait until threading._shutdown completes, provided
2393 the threading module was imported in the first place.
2394 The shutdown routine will wait until all non-daemon
2395 "threading" threads have completed. */
2396static void
2397wait_for_thread_shutdown(void)
2398{
2399#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002400 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 PyObject *result;
2402 PyThreadState *tstate = PyThreadState_GET();
2403 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2404 "threading");
2405 if (threading == NULL) {
2406 /* threading not imported */
2407 PyErr_Clear();
2408 return;
2409 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002410 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 if (result == NULL) {
2412 PyErr_WriteUnraisable(threading);
2413 }
2414 else {
2415 Py_DECREF(result);
2416 }
2417 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002418#endif
2419}
2420
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002421#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002422static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002423static int nexitfuncs = 0;
2424
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002425int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 if (nexitfuncs >= NEXITFUNCS)
2428 return -1;
2429 exitfuncs[nexitfuncs++] = func;
2430 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002431}
2432
Guido van Rossumcc283f51997-08-05 02:22:03 +00002433static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002434call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 while (nexitfuncs > 0)
2437 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 fflush(stdout);
2440 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002441}
2442
2443void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002444Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002449}
2450
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002451static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002452initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002453{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002454#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002456#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002457#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002459#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002460#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002462#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002464}
2465
Guido van Rossum7433b121997-02-14 19:45:36 +00002466
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002467/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2468 *
2469 * All of the code in this function must only use async-signal-safe functions,
2470 * listed at `man 7 signal` or
2471 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2472 */
2473void
2474_Py_RestoreSignals(void)
2475{
2476#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002478#endif
2479#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002481#endif
2482#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002484#endif
2485}
2486
2487
Guido van Rossum7433b121997-02-14 19:45:36 +00002488/*
2489 * The file descriptor fd is considered ``interactive'' if either
2490 * a) isatty(fd) is TRUE, or
2491 * b) the -i flag was given, and the filename associated with
2492 * the descriptor is NULL or "<stdin>" or "???".
2493 */
2494int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002495Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 if (isatty((int)fileno(fp)))
2498 return 1;
2499 if (!Py_InteractiveFlag)
2500 return 0;
2501 return (filename == NULL) ||
2502 (strcmp(filename, "<stdin>") == 0) ||
2503 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002504}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002505
2506
Tim Petersd08e3822003-04-17 15:24:21 +00002507#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002508#if defined(WIN32) && defined(_MSC_VER)
2509
2510/* Stack checking for Microsoft C */
2511
2512#include <malloc.h>
2513#include <excpt.h>
2514
Fred Drakee8de31c2000-08-31 05:38:39 +00002515/*
2516 * Return non-zero when we run out of memory on the stack; zero otherwise.
2517 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002518int
Fred Drake399739f2000-08-31 05:52:44 +00002519PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 __try {
2522 /* alloca throws a stack overflow exception if there's
2523 not enough space left on the stack */
2524 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2525 return 0;
2526 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2527 EXCEPTION_EXECUTE_HANDLER :
2528 EXCEPTION_CONTINUE_SEARCH) {
2529 int errcode = _resetstkoflw();
2530 if (errcode == 0)
2531 {
2532 Py_FatalError("Could not reset the stack!");
2533 }
2534 }
2535 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002536}
2537
2538#endif /* WIN32 && _MSC_VER */
2539
2540/* Alternate implementations can be added here... */
2541
2542#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002543
2544
2545/* Wrappers around sigaction() or signal(). */
2546
2547PyOS_sighandler_t
2548PyOS_getsig(int sig)
2549{
2550#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 struct sigaction context;
2552 if (sigaction(sig, NULL, &context) == -1)
2553 return SIG_ERR;
2554 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002555#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002557/* Special signal handling for the secure CRT in Visual Studio 2005 */
2558#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 switch (sig) {
2560 /* Only these signals are valid */
2561 case SIGINT:
2562 case SIGILL:
2563 case SIGFPE:
2564 case SIGSEGV:
2565 case SIGTERM:
2566 case SIGBREAK:
2567 case SIGABRT:
2568 break;
2569 /* Don't call signal() with other values or it will assert */
2570 default:
2571 return SIG_ERR;
2572 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002573#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 handler = signal(sig, SIG_IGN);
2575 if (handler != SIG_ERR)
2576 signal(sig, handler);
2577 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002578#endif
2579}
2580
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002581/*
2582 * All of the code in this function must only use async-signal-safe functions,
2583 * listed at `man 7 signal` or
2584 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2585 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002586PyOS_sighandler_t
2587PyOS_setsig(int sig, PyOS_sighandler_t handler)
2588{
2589#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 /* Some code in Modules/signalmodule.c depends on sigaction() being
2591 * used here if HAVE_SIGACTION is defined. Fix that if this code
2592 * changes to invalidate that assumption.
2593 */
2594 struct sigaction context, ocontext;
2595 context.sa_handler = handler;
2596 sigemptyset(&context.sa_mask);
2597 context.sa_flags = 0;
2598 if (sigaction(sig, &context, &ocontext) == -1)
2599 return SIG_ERR;
2600 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002601#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 PyOS_sighandler_t oldhandler;
2603 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002604#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002606#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002608#endif
2609}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002610
2611/* Deprecated C API functions still provided for binary compatiblity */
2612
2613#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002614PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002615PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002618}
2619
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002620#undef PyParser_SimpleParseString
2621PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622PyParser_SimpleParseString(const char *str, int start)
2623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002625}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002626
2627#undef PyRun_AnyFile
2628PyAPI_FUNC(int)
2629PyRun_AnyFile(FILE *fp, const char *name)
2630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002632}
2633
2634#undef PyRun_AnyFileEx
2635PyAPI_FUNC(int)
2636PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002639}
2640
2641#undef PyRun_AnyFileFlags
2642PyAPI_FUNC(int)
2643PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002646}
2647
2648#undef PyRun_File
2649PyAPI_FUNC(PyObject *)
2650PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002653}
2654
2655#undef PyRun_FileEx
2656PyAPI_FUNC(PyObject *)
2657PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002660}
2661
2662#undef PyRun_FileFlags
2663PyAPI_FUNC(PyObject *)
2664PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002668}
2669
2670#undef PyRun_SimpleFile
2671PyAPI_FUNC(int)
2672PyRun_SimpleFile(FILE *f, const char *p)
2673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002675}
2676
2677#undef PyRun_SimpleFileEx
2678PyAPI_FUNC(int)
2679PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002682}
2683
2684
2685#undef PyRun_String
2686PyAPI_FUNC(PyObject *)
2687PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002690}
2691
2692#undef PyRun_SimpleString
2693PyAPI_FUNC(int)
2694PyRun_SimpleString(const char *s)
2695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002697}
2698
2699#undef Py_CompileString
2700PyAPI_FUNC(PyObject *)
2701Py_CompileString(const char *str, const char *p, int s)
2702{
Georg Brandl8334fd92010-12-04 10:26:46 +00002703 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2704}
2705
2706#undef Py_CompileStringFlags
2707PyAPI_FUNC(PyObject *)
2708Py_CompileStringFlags(const char *str, const char *p, int s,
2709 PyCompilerFlags *flags)
2710{
2711 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002712}
2713
2714#undef PyRun_InteractiveOne
2715PyAPI_FUNC(int)
2716PyRun_InteractiveOne(FILE *f, const char *p)
2717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002719}
2720
2721#undef PyRun_InteractiveLoop
2722PyAPI_FUNC(int)
2723PyRun_InteractiveLoop(FILE *f, const char *p)
2724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002726}
2727
2728#ifdef __cplusplus
2729}
2730#endif