blob: 91d56b78eea21cf1a848954226abf3a142fffd08 [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 Pitrouf95a1b32010-05-09 15:52:27 +000041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
43 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#endif
45
46#ifdef __cplusplus
47extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000048#endif
49
Martin v. Löwis790465f2008-04-05 20:41:37 +000050extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000051
Guido van Rossum82598051997-03-05 00:20:32 +000052extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossumb73cc041993-11-01 16:28:59 +000054/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100055static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020056static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020065static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000067static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000068static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000069static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +020070extern int _PyUnicode_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000071extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020074extern int _PyFaulthandler_Init(void);
75extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000084int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000085int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020086int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000087int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000088int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000089int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000090int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000091int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000092int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000094int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +010095int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000096
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020097PyThreadState *_Py_Finalizing = NULL;
98
Christian Heimes49e61802013-10-22 10:22:29 +020099/* Hack to force loading of object files */
100int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
101 PyOS_mystrnicmp; /* Python/pystrcmp.o */
102
Christian Heimes33fe8092008-04-13 13:53:33 +0000103/* PyModule_GetWarningsModule is no longer necessary as of 2.6
104since _warnings is builtin. This API should not be used. */
105PyObject *
106PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000109}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000110
Guido van Rossum25ce5661997-08-02 03:10:38 +0000111static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000112
Thomas Wouters7e474022000-07-16 12:04:32 +0000113/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000114
115int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000116Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000119}
120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121/* Global initializations. Can be undone by Py_Finalize(). Don't
122 call this twice without an intervening Py_Finalize() call. When
123 initializations fail, a fatal error is issued and the function does
124 not return. On return, the first thread and interpreter state have
125 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000126
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127 Locking: you must hold the interpreter lock while calling this.
128 (If the lock has not yet been initialized, that's equivalent to
129 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000130
Guido van Rossum25ce5661997-08-02 03:10:38 +0000131*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000132
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000133static int
134add_flag(int flag, const char *envs)
135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 int env = atoi(envs);
137 if (flag < env)
138 flag = env;
139 if (flag < 1)
140 flag = 1;
141 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000142}
143
Christian Heimes5833a2f2008-10-30 21:40:04 +0000144static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000145get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000146{
Victor Stinner94908bb2010-08-18 21:23:25 +0000147 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000148 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200149 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000150
Victor Stinner94908bb2010-08-18 21:23:25 +0000151 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 if (!codec)
153 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000154
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200155 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 Py_CLEAR(codec);
157 if (!name)
158 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000159
Victor Stinner94908bb2010-08-18 21:23:25 +0000160 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100161 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000162 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000163 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000165 if (name_str == NULL) {
166 PyErr_NoMemory();
167 return NULL;
168 }
169 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000170
171error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000173 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000175}
Victor Stinner94908bb2010-08-18 21:23:25 +0000176
Victor Stinner94908bb2010-08-18 21:23:25 +0000177static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200178get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000179{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200180#ifdef MS_WINDOWS
181 char codepage[100];
182 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
183 return get_codec_name(codepage);
184#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000185 char* codeset = nl_langinfo(CODESET);
186 if (!codeset || codeset[0] == '\0') {
187 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
188 return NULL;
189 }
190 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200191#else
192 PyErr_SetNone(PyExc_NotImplementedError);
193 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000194#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200195}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000196
Brett Cannonfd074152012-04-14 14:10:13 -0400197static void
198import_init(PyInterpreterState *interp, PyObject *sysmod)
199{
200 PyObject *importlib;
201 PyObject *impmod;
202 PyObject *sys_modules;
203 PyObject *value;
204
205 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400206 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
207 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
208 }
209 else if (Py_VerboseFlag) {
210 PySys_FormatStderr("import _frozen_importlib # frozen\n");
211 }
212 importlib = PyImport_AddModule("_frozen_importlib");
213 if (importlib == NULL) {
214 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
215 "sys.modules");
216 }
217 interp->importlib = importlib;
218 Py_INCREF(interp->importlib);
219
220 /* Install _importlib as __import__ */
221 impmod = PyInit_imp();
222 if (impmod == NULL) {
223 Py_FatalError("Py_Initialize: can't import imp");
224 }
225 else if (Py_VerboseFlag) {
226 PySys_FormatStderr("import imp # builtin\n");
227 }
228 sys_modules = PyImport_GetModuleDict();
229 if (Py_VerboseFlag) {
230 PySys_FormatStderr("import sys # builtin\n");
231 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400232 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
233 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400234 }
235
Brett Cannone0d88a12012-04-25 20:54:04 -0400236 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400237 if (value == NULL) {
238 PyErr_Print();
239 Py_FatalError("Py_Initialize: importlib install failed");
240 }
241 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400242 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400243
244 _PyImportZip_Init();
245}
246
247
Guido van Rossuma027efa1997-05-05 20:56:21 +0000248void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200249_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 PyInterpreterState *interp;
252 PyThreadState *tstate;
253 PyObject *bimod, *sysmod, *pstderr;
254 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 if (initialized)
258 return;
259 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200260 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000261
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000262#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 /* Set up the LC_CTYPE locale, so we can obtain
264 the locale's charset without having to switch
265 locales. */
266 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000267#endif
268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
270 Py_DebugFlag = add_flag(Py_DebugFlag, p);
271 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
272 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
273 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
274 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
275 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
276 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100277 /* The variable is only tested for existence here; _PyRandom_Init will
278 check its value further. */
279 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
280 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
281
282 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 interp = PyInterpreterState_New();
285 if (interp == NULL)
286 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 tstate = PyThreadState_New(interp);
289 if (tstate == NULL)
290 Py_FatalError("Py_Initialize: can't make first thread");
291 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000292
Victor Stinner6961bd62010-08-17 22:26:51 +0000293#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000294 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
295 destroying the GIL might fail when it is being referenced from
296 another running thread (see issue #9901).
297 Instead we destroy the previously created GIL here, which ensures
298 that we can call Py_Initialize / Py_Finalize multiple times. */
299 _PyEval_FiniThreads();
300
301 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000302 _PyGILState_Init(interp, tstate);
303#endif /* WITH_THREAD */
304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (!_PyFrame_Init())
308 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (!_PyLong_Init())
311 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 if (!PyByteArray_Init())
314 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 interp->modules = PyDict_New();
319 if (interp->modules == NULL)
320 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200323 if (_PyUnicode_Init() < 0)
324 Py_FatalError("Py_Initialize: can't initialize unicode");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 bimod = _PyBuiltin_Init();
327 if (bimod == NULL)
328 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000329 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 interp->builtins = PyModule_GetDict(bimod);
331 if (interp->builtins == NULL)
332 Py_FatalError("Py_Initialize: can't initialize builtins dict");
333 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400336 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 sysmod = _PySys_Init();
339 if (sysmod == NULL)
340 Py_FatalError("Py_Initialize: can't initialize sys");
341 interp->sysdict = PyModule_GetDict(sysmod);
342 if (interp->sysdict == NULL)
343 Py_FatalError("Py_Initialize: can't initialize sys dict");
344 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000345 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 PySys_SetPath(Py_GetPath());
347 PyDict_SetItemString(interp->sysdict, "modules",
348 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 /* Set up a preliminary stderr printer until we have enough
351 infrastructure for the io module in place. */
352 pstderr = PyFile_NewStdPrinter(fileno(stderr));
353 if (pstderr == NULL)
354 Py_FatalError("Py_Initialize: can't set preliminary stderr");
355 PySys_SetObject("stderr", pstderr);
356 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000357 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000362
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000363 /* Initialize _warnings. */
364 _PyWarnings_Init();
365
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200366 if (!install_importlib)
367 return;
368
Brett Cannonfd074152012-04-14 14:10:13 -0400369 import_init(interp, sysmod);
370
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200371 /* initialize the faulthandler module */
372 if (_PyFaulthandler_Init())
373 Py_FatalError("Py_Initialize: can't initialize faulthandler");
374
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000375 _PyTime_Init();
376
Victor Stinner793b5312011-04-27 00:24:21 +0200377 if (initfsencoding(interp) < 0)
378 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 if (install_sigs)
381 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000382
Nick Coghlan85e729e2012-07-15 18:09:52 +1000383 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (initstdio() < 0)
385 Py_FatalError(
386 "Py_Initialize: can't initialize sys standard streams");
387
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000388 /* Initialize warnings. */
389 if (PySys_HasWarnOptions()) {
390 PyObject *warnings_module = PyImport_ImportModule("warnings");
391 if (warnings_module == NULL) {
392 fprintf(stderr, "'import warnings' failed; traceback:\n");
393 PyErr_Print();
394 }
395 Py_XDECREF(warnings_module);
396 }
397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 if (!Py_NoSiteFlag)
399 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000400}
401
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000402void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200403Py_InitializeEx(int install_sigs)
404{
405 _Py_InitializeEx_Private(install_sigs, 1);
406}
407
408void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000409Py_Initialize(void)
410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000412}
413
414
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000415#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000416extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000417#endif
418
Guido van Rossume8432ac2007-07-09 15:04:50 +0000419/* Flush stdout and stderr */
420
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100421static int
422file_is_closed(PyObject *fobj)
423{
424 int r;
425 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
426 if (tmp == NULL) {
427 PyErr_Clear();
428 return 0;
429 }
430 r = PyObject_IsTrue(tmp);
431 Py_DECREF(tmp);
432 if (r < 0)
433 PyErr_Clear();
434 return r > 0;
435}
436
Neal Norwitz2bad9702007-08-27 06:19:22 +0000437static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000438flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 PyObject *fout = PySys_GetObject("stdout");
441 PyObject *ferr = PySys_GetObject("stderr");
442 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200443 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000444
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100445 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200446 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000448 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 else
450 Py_DECREF(tmp);
451 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000452
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100453 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200454 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (tmp == NULL)
456 PyErr_Clear();
457 else
458 Py_DECREF(tmp);
459 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000460}
461
Guido van Rossum25ce5661997-08-02 03:10:38 +0000462/* Undo the effect of Py_Initialize().
463
464 Beware: if multiple interpreter and/or thread states exist, these
465 are not wiped out; only the current thread and interpreter state
466 are deleted. But since everything else is deleted, those other
467 interpreter and thread states should no longer be used.
468
469 (XXX We should do better, e.g. wipe out all interpreters and
470 threads.)
471
472 Locking: as above.
473
474*/
475
476void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000477Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyInterpreterState *interp;
480 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (!initialized)
483 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 /* The interpreter is still entirely intact at this point, and the
488 * exit funcs may be relying on that. In particular, if some thread
489 * or exit func is still waiting to do an import, the import machinery
490 * expects Py_IsInitialized() to return true. So don't say the
491 * interpreter is uninitialized until after the exit funcs have run.
492 * Note that Threading.py uses an exit func to do a join on all the
493 * threads created thru it, so this also protects pending imports in
494 * the threads created via Threading.
495 */
496 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 /* Get current thread state and interpreter pointer */
499 tstate = PyThreadState_GET();
500 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000501
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200502 /* Remaining threads (e.g. daemon threads) will automatically exit
503 after taking the GIL (in PyEval_RestoreThread()). */
504 _Py_Finalizing = tstate;
505 initialized = 0;
506
507 /* Flush stdout+stderr */
508 flush_std_files();
509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* Disable signal handling */
511 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +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
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200565 /* Cleanup typeobject.c's internal caches. */
566 _PyType_Fini();
567
Victor Stinner024e37a2011-03-31 01:31:06 +0200568 /* unload faulthandler module */
569 _PyFaulthandler_Fini();
570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000572#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000574#endif
575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000577
Tim Peters9cf25ce2003-04-17 15:21:01 +0000578#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 /* Display all objects still alive -- this can invoke arbitrary
580 * __repr__ overrides, so requires a mostly-intact interpreter.
581 * Alas, a lot of stuff may still be alive now that will be cleaned
582 * up later.
583 */
584 if (Py_GETENV("PYTHONDUMPREFS"))
585 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000586#endif /* Py_TRACE_REFS */
587
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200588 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 /* Now we decref the exception classes. After this point nothing
592 can raise an exception. That's okay, because each Fini() method
593 below has been checked to make sure no exceptions are ever
594 raised.
595 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000600#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000602#endif /* WITH_THREAD */
603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 /* Sundry finalizers */
605 PyMethod_Fini();
606 PyFrame_Fini();
607 PyCFunction_Fini();
608 PyTuple_Fini();
609 PyList_Fini();
610 PySet_Fini();
611 PyBytes_Fini();
612 PyByteArray_Fini();
613 PyLong_Fini();
614 PyFloat_Fini();
615 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100616 PySlice_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 /* Cleanup Unicode implementation */
619 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000620
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200621 /* Delete current thread. After this, many C API calls become crashy. */
622 PyThreadState_Swap(NULL);
623 PyInterpreterState_Delete(interp);
624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000626 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 free((char*)Py_FileSystemDefaultEncoding);
628 Py_FileSystemDefaultEncoding = NULL;
629 }
Christian Heimesc8967002007-11-30 10:18:26 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 /* XXX Still allocated:
632 - various static ad-hoc pointers to interned strings
633 - int and float free list blocks
634 - whatever various modules and libraries allocate
635 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000638
Tim Peters269b2a62003-04-17 19:52:29 +0000639#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 /* Display addresses (& refcnts) of all objects still alive.
641 * An address can be used to find the repr of the object, printed
642 * above by _Py_PrintReferences.
643 */
644 if (Py_GETENV("PYTHONDUMPREFS"))
645 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000646#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000647#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400649 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000650#endif
651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000653}
654
655/* Create and initialize a new interpreter and thread, and return the
656 new thread. This requires that Py_Initialize() has been called
657 first.
658
659 Unsuccessful initialization yields a NULL pointer. Note that *no*
660 exception information is available even in this case -- the
661 exception information is held in the thread, and there is no
662 thread.
663
664 Locking: as above.
665
666*/
667
668PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000669Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 PyInterpreterState *interp;
672 PyThreadState *tstate, *save_tstate;
673 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 if (!initialized)
676 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 interp = PyInterpreterState_New();
679 if (interp == NULL)
680 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 tstate = PyThreadState_New(interp);
683 if (tstate == NULL) {
684 PyInterpreterState_Delete(interp);
685 return NULL;
686 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000693
Victor Stinner49d3f252010-10-17 01:24:53 +0000694 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (bimod != NULL) {
696 interp->builtins = PyModule_GetDict(bimod);
697 if (interp->builtins == NULL)
698 goto handle_error;
699 Py_INCREF(interp->builtins);
700 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400703 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000704
Victor Stinner49d3f252010-10-17 01:24:53 +0000705 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (bimod != NULL && sysmod != NULL) {
707 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 interp->sysdict = PyModule_GetDict(sysmod);
710 if (interp->sysdict == NULL)
711 goto handle_error;
712 Py_INCREF(interp->sysdict);
713 PySys_SetPath(Py_GetPath());
714 PyDict_SetItemString(interp->sysdict, "modules",
715 interp->modules);
716 /* Set up a preliminary stderr printer until we have enough
717 infrastructure for the io module in place. */
718 pstderr = PyFile_NewStdPrinter(fileno(stderr));
719 if (pstderr == NULL)
720 Py_FatalError("Py_Initialize: can't set preliminary stderr");
721 PySys_SetObject("stderr", pstderr);
722 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000723 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200726
Brett Cannonfd074152012-04-14 14:10:13 -0400727 import_init(interp, sysmod);
728
Victor Stinner793b5312011-04-27 00:24:21 +0200729 if (initfsencoding(interp) < 0)
730 goto handle_error;
731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (initstdio() < 0)
733 Py_FatalError(
734 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000735 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (!Py_NoSiteFlag)
737 initsite();
738 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 if (!PyErr_Occurred())
741 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000742
Thomas Wouters89f507f2006-12-13 04:49:30 +0000743handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000745
Victor Stinnerc40a3502011-04-27 00:20:27 +0200746 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyThreadState_Clear(tstate);
748 PyThreadState_Swap(save_tstate);
749 PyThreadState_Delete(tstate);
750 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000753}
754
755/* Delete an interpreter and its last thread. This requires that the
756 given thread state is current, that the thread has no remaining
757 frames, and that it is its interpreter's only remaining thread.
758 It is a fatal error to violate these constraints.
759
760 (Py_Finalize() doesn't have these constraints -- it zaps
761 everything, regardless.)
762
763 Locking: as above.
764
765*/
766
767void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000768Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 if (tstate != PyThreadState_GET())
773 Py_FatalError("Py_EndInterpreter: thread is not current");
774 if (tstate->frame != NULL)
775 Py_FatalError("Py_EndInterpreter: thread still has a frame");
776 if (tstate != interp->tstate_head || tstate->next != NULL)
777 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyImport_Cleanup();
780 PyInterpreterState_Clear(interp);
781 PyThreadState_Swap(NULL);
782 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000783}
784
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200785#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000786static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200787#else
788static wchar_t *progname = L"python3";
789#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000790
791void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000792Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 if (pn && *pn)
795 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000796}
797
Martin v. Löwis790465f2008-04-05 20:41:37 +0000798wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000799Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000802}
803
Martin v. Löwis790465f2008-04-05 20:41:37 +0000804static wchar_t *default_home = NULL;
805static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000806
807void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000808Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000811}
812
Martin v. Löwis790465f2008-04-05 20:41:37 +0000813wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000814Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 wchar_t *home = default_home;
817 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
818 char* chome = Py_GETENV("PYTHONHOME");
819 if (chome) {
Victor Stinner2f5bbc62013-11-15 17:09:24 +0100820 size_t size = Py_ARRAY_LENGTH(env_home);
821 size_t r = mbstowcs(env_home, chome, size);
822 if (r != (size_t)-1 && r < size)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 home = env_home;
824 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 }
827 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000828}
829
Guido van Rossum6135a871995-01-09 17:53:26 +0000830/* Create __main__ module */
831
832static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000833initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *m, *d;
836 m = PyImport_AddModule("__main__");
837 if (m == NULL)
838 Py_FatalError("can't create __main__ module");
839 d = PyModule_GetDict(m);
840 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
841 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000842 if (bimod == NULL) {
843 Py_FatalError("Failed to retrieve builtins module");
844 }
845 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
846 Py_FatalError("Failed to initialize __main__.__builtins__");
847 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 Py_DECREF(bimod);
849 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000850 /* Main is a little special - imp.is_builtin("__main__") will return
851 * False, but BuiltinImporter is still the most appropriate initial
852 * setting for its __loader__ attribute. A more suitable value will
853 * be set if __main__ gets further initialized later in the startup
854 * process.
855 */
856 if (PyDict_GetItemString(d, "__loader__") == NULL) {
857 PyObject *loader = PyObject_GetAttrString(interp->importlib,
858 "BuiltinImporter");
859 if (loader == NULL) {
860 Py_FatalError("Failed to retrieve BuiltinImporter");
861 }
862 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
863 Py_FatalError("Failed to initialize __main__.__loader__");
864 }
865 Py_DECREF(loader);
866 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000867}
868
Victor Stinner793b5312011-04-27 00:24:21 +0200869static int
870initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000871{
872 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000873
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200874 if (Py_FileSystemDefaultEncoding == NULL)
875 {
876 Py_FileSystemDefaultEncoding = get_locale_encoding();
877 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000878 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000879
Victor Stinnere4743092010-10-19 00:05:51 +0000880 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200881 interp->fscodec_initialized = 1;
882 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000883 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000884
885 /* the encoding is mbcs, utf-8 or ascii */
886 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
887 if (!codec) {
888 /* Such error can only occurs in critical situations: no more
889 * memory, import a module of the standard library failed,
890 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200891 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000892 }
Victor Stinner793b5312011-04-27 00:24:21 +0200893 Py_DECREF(codec);
894 interp->fscodec_initialized = 1;
895 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000896}
897
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000898/* Import the site module (not into __main__ though) */
899
900static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000901initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 PyObject *m;
904 m = PyImport_ImportModule("site");
905 if (m == NULL) {
906 PyErr_Print();
907 Py_Finalize();
908 exit(1);
909 }
910 else {
911 Py_DECREF(m);
912 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000913}
914
Antoine Pitrou05608432009-01-09 18:53:14 +0000915static PyObject*
916create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 int fd, int write_mode, char* name,
918 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
921 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000922 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 PyObject *line_buffering;
924 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200925 _Py_IDENTIFIER(open);
926 _Py_IDENTIFIER(isatty);
927 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200928 _Py_IDENTIFIER(name);
929 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* stdin is always opened in buffered mode, first because it shouldn't
932 make a difference in common use cases, second because TextIOWrapper
933 depends on the presence of a read1() method which only exists on
934 buffered streams.
935 */
936 if (Py_UnbufferedStdioFlag && write_mode)
937 buffering = 0;
938 else
939 buffering = -1;
940 if (write_mode)
941 mode = "wb";
942 else
943 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200944 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
945 fd, mode, buffering,
946 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 if (buf == NULL)
948 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200951 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200952 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (raw == NULL)
954 goto error;
955 }
956 else {
957 raw = buf;
958 Py_INCREF(raw);
959 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200962 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200964 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 if (res == NULL)
966 goto error;
967 isatty = PyObject_IsTrue(res);
968 Py_DECREF(res);
969 if (isatty == -1)
970 goto error;
971 if (isatty || Py_UnbufferedStdioFlag)
972 line_buffering = Py_True;
973 else
974 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 Py_CLEAR(raw);
977 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000978
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000979#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +0200980 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
981 newlines to "\n".
982 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
983 newline = NULL;
984#else
985 /* sys.stdin: split lines at "\n".
986 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
987 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000988#endif
989
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200990 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
991 buf, encoding, errors,
992 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 Py_CLEAR(buf);
994 if (stream == NULL)
995 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (write_mode)
998 mode = "w";
999 else
1000 mode = "r";
1001 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001002 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 goto error;
1004 Py_CLEAR(text);
1005 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001006
1007error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 Py_XDECREF(buf);
1009 Py_XDECREF(stream);
1010 Py_XDECREF(text);
1011 Py_XDECREF(raw);
1012 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001013}
1014
Antoine Pitrou11942a52011-11-28 19:08:36 +01001015static int
1016is_valid_fd(int fd)
1017{
1018 int dummy_fd;
1019 if (fd < 0 || !_PyVerify_fd(fd))
1020 return 0;
1021 dummy_fd = dup(fd);
1022 if (dummy_fd < 0)
1023 return 0;
1024 close(dummy_fd);
1025 return 1;
1026}
1027
Georg Brandl1a3284e2007-12-02 09:40:06 +00001028/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001029static int
1030initstdio(void)
1031{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 PyObject *iomod = NULL, *wrapper;
1033 PyObject *bimod = NULL;
1034 PyObject *m;
1035 PyObject *std = NULL;
1036 int status = 0, fd;
1037 PyObject * encoding_attr;
1038 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 /* Hack to avoid a nasty recursion issue when Python is invoked
1041 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1042 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1043 goto error;
1044 }
1045 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1048 goto error;
1049 }
1050 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 if (!(bimod = PyImport_ImportModule("builtins"))) {
1053 goto error;
1054 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (!(iomod = PyImport_ImportModule("io"))) {
1057 goto error;
1058 }
1059 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1060 goto error;
1061 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 /* Set builtins.open */
1064 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001065 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 goto error;
1067 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001068 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 encoding = Py_GETENV("PYTHONIOENCODING");
1071 errors = NULL;
1072 if (encoding) {
1073 encoding = strdup(encoding);
1074 errors = strchr(encoding, ':');
1075 if (errors) {
1076 *errors = '\0';
1077 errors++;
1078 }
1079 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 /* Set sys.stdin */
1082 fd = fileno(stdin);
1083 /* Under some conditions stdin, stdout and stderr may not be connected
1084 * and fileno() may point to an invalid file descriptor. For example
1085 * GUI apps don't have valid standard streams by default.
1086 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001087 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 std = Py_None;
1089 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 }
1091 else {
1092 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1093 if (std == NULL)
1094 goto error;
1095 } /* if (fd < 0) */
1096 PySys_SetObject("__stdin__", std);
1097 PySys_SetObject("stdin", std);
1098 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 /* Set sys.stdout */
1101 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001102 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 std = Py_None;
1104 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 }
1106 else {
1107 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1108 if (std == NULL)
1109 goto error;
1110 } /* if (fd < 0) */
1111 PySys_SetObject("__stdout__", std);
1112 PySys_SetObject("stdout", std);
1113 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001114
Guido van Rossum98297ee2007-11-06 21:34:58 +00001115#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 /* Set sys.stderr, replaces the preliminary stderr */
1117 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001118 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 std = Py_None;
1120 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 }
1122 else {
1123 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1124 if (std == NULL)
1125 goto error;
1126 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 /* Same as hack above, pre-import stderr's codec to avoid recursion
1129 when import.c tries to write to stderr in verbose mode. */
1130 encoding_attr = PyObject_GetAttrString(std, "encoding");
1131 if (encoding_attr != NULL) {
1132 const char * encoding;
1133 encoding = _PyUnicode_AsString(encoding_attr);
1134 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001135 PyObject *codec_info = _PyCodec_Lookup(encoding);
1136 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001138 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 }
1140 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 PySys_SetObject("__stderr__", std);
1143 PySys_SetObject("stderr", std);
1144 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001145#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001148 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 status = -1;
1150 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (encoding)
1153 free(encoding);
1154 Py_XDECREF(bimod);
1155 Py_XDECREF(iomod);
1156 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001157}
1158
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001159/* Parse input from a file and execute it */
1160
1161int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001162PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (filename == NULL)
1166 filename = "???";
1167 if (Py_FdIsInteractive(fp, filename)) {
1168 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1169 if (closeit)
1170 fclose(fp);
1171 return err;
1172 }
1173 else
1174 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001175}
1176
1177int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001178PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 PyObject *v;
1181 int ret;
1182 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (flags == NULL) {
1185 flags = &local_flags;
1186 local_flags.cf_flags = 0;
1187 }
1188 v = PySys_GetObject("ps1");
1189 if (v == NULL) {
1190 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1191 Py_XDECREF(v);
1192 }
1193 v = PySys_GetObject("ps2");
1194 if (v == NULL) {
1195 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1196 Py_XDECREF(v);
1197 }
1198 for (;;) {
1199 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1200 PRINT_TOTAL_REFS();
1201 if (ret == E_EOF)
1202 return 0;
1203 /*
1204 if (ret == E_NOMEM)
1205 return -1;
1206 */
1207 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001208}
1209
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001210/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001211static int PARSER_FLAGS(PyCompilerFlags *flags)
1212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 int parser_flags = 0;
1214 if (!flags)
1215 return 0;
1216 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1217 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1218 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1219 parser_flags |= PyPARSE_IGNORE_COOKIE;
1220 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1221 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1222 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001223}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001224
Thomas Wouters89f507f2006-12-13 04:49:30 +00001225#if 0
1226/* Keep an example of flags with future keyword support. */
1227#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1229 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1230 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1231 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001232#endif
1233
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001234int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001235PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 PyObject *m, *d, *v, *w, *oenc = NULL;
1238 mod_ty mod;
1239 PyArena *arena;
1240 char *ps1 = "", *ps2 = "", *enc = NULL;
1241 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001242 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001245 /* Fetch encoding from sys.stdin if possible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 v = PySys_GetObject("stdin");
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001247 if (v && v != Py_None) {
1248 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1249 if (oenc)
1250 enc = _PyUnicode_AsString(oenc);
1251 if (!enc)
1252 PyErr_Clear();
1253 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 }
1255 v = PySys_GetObject("ps1");
1256 if (v != NULL) {
1257 v = PyObject_Str(v);
1258 if (v == NULL)
1259 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001260 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001262 if (ps1 == NULL) {
1263 PyErr_Clear();
1264 ps1 = "";
1265 }
1266 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 }
1268 w = PySys_GetObject("ps2");
1269 if (w != NULL) {
1270 w = PyObject_Str(w);
1271 if (w == NULL)
1272 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001273 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001275 if (ps2 == NULL) {
1276 PyErr_Clear();
1277 ps2 = "";
1278 }
1279 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 }
1281 arena = PyArena_New();
1282 if (arena == NULL) {
1283 Py_XDECREF(v);
1284 Py_XDECREF(w);
1285 Py_XDECREF(oenc);
1286 return -1;
1287 }
1288 mod = PyParser_ASTFromFile(fp, filename, enc,
1289 Py_single_input, ps1, ps2,
1290 flags, &errcode, arena);
1291 Py_XDECREF(v);
1292 Py_XDECREF(w);
1293 Py_XDECREF(oenc);
1294 if (mod == NULL) {
1295 PyArena_Free(arena);
1296 if (errcode == E_EOF) {
1297 PyErr_Clear();
1298 return E_EOF;
1299 }
1300 PyErr_Print();
1301 return -1;
1302 }
1303 m = PyImport_AddModule("__main__");
1304 if (m == NULL) {
1305 PyArena_Free(arena);
1306 return -1;
1307 }
1308 d = PyModule_GetDict(m);
1309 v = run_mod(mod, filename, d, d, flags, arena);
1310 PyArena_Free(arena);
1311 flush_io();
1312 if (v == NULL) {
1313 PyErr_Print();
1314 return -1;
1315 }
1316 Py_DECREF(v);
1317 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001318}
1319
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001320/* Check whether a file maybe a pyc file: Look at the extension,
1321 the file type, and, if we may close it, at the first few bytes. */
1322
1323static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001324maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1327 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 /* Only look into the file if we are allowed to close it, since
1330 it then should also be seekable. */
1331 if (closeit) {
1332 /* Read only two bytes of the magic. If the file was opened in
1333 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1334 be read as they are on disk. */
1335 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1336 unsigned char buf[2];
1337 /* Mess: In case of -x, the stream is NOT at its start now,
1338 and ungetc() was used to push back the first newline,
1339 which makes the current stream position formally undefined,
1340 and a x-platform nightmare.
1341 Unfortunately, we have no direct way to know whether -x
1342 was specified. So we use a terrible hack: if the current
1343 stream position is not 0, we assume -x was specified, and
1344 give up. Bug 132850 on SourceForge spells out the
1345 hopelessness of trying anything else (fseek and ftell
1346 don't work predictably x-platform for text-mode files).
1347 */
1348 int ispyc = 0;
1349 if (ftell(fp) == 0) {
1350 if (fread(buf, 1, 2, fp) == 2 &&
1351 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1352 ispyc = 1;
1353 rewind(fp);
1354 }
1355 return ispyc;
1356 }
1357 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001358}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001359
Guido van Rossum0df002c2000-08-27 19:21:52 +00001360int
Nick Coghlanceda83c2012-07-15 23:18:08 +10001361static set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001362{
1363 PyInterpreterState *interp;
1364 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001365 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001366 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001367
1368 filename_obj = PyUnicode_DecodeFSDefault(filename);
1369 if (filename_obj == NULL)
1370 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001371 /* Get current thread state and interpreter pointer */
1372 tstate = PyThreadState_GET();
1373 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001374 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1375 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001376 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001377 return -1;
1378 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001379 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001380 Py_DECREF(loader_type);
1381 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001382 return -1;
1383 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001384 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1385 result = -1;
1386 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001387 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001388 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001389}
1390
1391int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001392PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 PyObject *m, *d, *v;
1396 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001397 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001398 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 m = PyImport_AddModule("__main__");
1401 if (m == NULL)
1402 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001403 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 d = PyModule_GetDict(m);
1405 if (PyDict_GetItemString(d, "__file__") == NULL) {
1406 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001407 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001409 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1411 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001412 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001414 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1415 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001416 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001417 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 set_file_name = 1;
1419 Py_DECREF(f);
1420 }
1421 len = strlen(filename);
1422 ext = filename + len - (len > 4 ? 4 : 0);
1423 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001424 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 /* Try to run a pyc file. First, re-open in binary */
1426 if (closeit)
1427 fclose(fp);
Christian Heimes04ac4c12012-09-11 15:47:28 +02001428 if ((pyc_fp = fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 goto done;
1431 }
1432 /* Turn on optimization if a .pyo file is given */
1433 if (strcmp(ext, ".pyo") == 0)
1434 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001435
1436 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1437 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1438 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001439 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001440 goto done;
1441 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001442 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1443 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001445 /* When running from stdin, leave __main__.__loader__ alone */
1446 if (strcmp(filename, "<stdin>") != 0 &&
1447 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1448 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1449 ret = -1;
1450 goto done;
1451 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1453 closeit, flags);
1454 }
1455 flush_io();
1456 if (v == NULL) {
1457 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 goto done;
1459 }
1460 Py_DECREF(v);
1461 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001462 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1464 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001465 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001467}
1468
1469int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001470PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 PyObject *m, *d, *v;
1473 m = PyImport_AddModule("__main__");
1474 if (m == NULL)
1475 return -1;
1476 d = PyModule_GetDict(m);
1477 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1478 if (v == NULL) {
1479 PyErr_Print();
1480 return -1;
1481 }
1482 Py_DECREF(v);
1483 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001484}
1485
Barry Warsaw035574d1997-08-29 22:07:17 +00001486static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001487parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 long hold;
1491 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001492 _Py_IDENTIFIER(msg);
1493 _Py_IDENTIFIER(filename);
1494 _Py_IDENTIFIER(lineno);
1495 _Py_IDENTIFIER(offset);
1496 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001497
Benjamin Peterson80d50422012-04-03 00:30:38 -04001498 *message = NULL;
1499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001501 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001502 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001504
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001505 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001506 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001508 if (v == Py_None) {
1509 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001511 }
1512 else {
1513 *filename = _PyUnicode_AsString(v);
1514 Py_DECREF(v);
1515 if (!*filename)
1516 goto finally;
1517 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001518
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001519 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001520 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 goto finally;
1522 hold = PyLong_AsLong(v);
1523 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 if (hold < 0 && PyErr_Occurred())
1525 goto finally;
1526 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001527
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001528 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001529 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 goto finally;
1531 if (v == Py_None) {
1532 *offset = -1;
1533 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 } else {
1535 hold = PyLong_AsLong(v);
1536 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (hold < 0 && PyErr_Occurred())
1538 goto finally;
1539 *offset = (int)hold;
1540 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001541
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001542 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001543 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001545 if (v == Py_None) {
1546 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001548 }
1549 else {
1550 *text = _PyUnicode_AsString(v);
1551 Py_DECREF(v);
1552 if (!*text)
1553 goto finally;
1554 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001556
1557finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001558 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001560}
1561
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001562void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001563PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001566}
1567
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001568static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001569print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 char *nl;
1572 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001573 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1574 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 for (;;) {
1576 nl = strchr(text, '\n');
1577 if (nl == NULL || nl-text >= offset)
1578 break;
1579 offset -= (int)(nl+1-text);
1580 text = nl+1;
1581 }
1582 while (*text == ' ' || *text == '\t') {
1583 text++;
1584 offset--;
1585 }
1586 }
1587 PyFile_WriteString(" ", f);
1588 PyFile_WriteString(text, f);
1589 if (*text == '\0' || text[strlen(text)-1] != '\n')
1590 PyFile_WriteString("\n", f);
1591 if (offset == -1)
1592 return;
1593 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001594 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001597}
1598
Guido van Rossum66e8e862001-03-23 17:54:43 +00001599static void
1600handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 PyObject *exception, *value, *tb;
1603 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 if (Py_InspectFlag)
1606 /* Don't exit if -i flag was given. This flag is set to 0
1607 * when entering interactive mode for inspecting. */
1608 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 PyErr_Fetch(&exception, &value, &tb);
1611 fflush(stdout);
1612 if (value == NULL || value == Py_None)
1613 goto done;
1614 if (PyExceptionInstance_Check(value)) {
1615 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001616 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001617 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (code) {
1619 Py_DECREF(value);
1620 value = code;
1621 if (value == Py_None)
1622 goto done;
1623 }
1624 /* If we failed to dig out the 'code' attribute,
1625 just let the else clause below print the error. */
1626 }
1627 if (PyLong_Check(value))
1628 exitcode = (int)PyLong_AsLong(value);
1629 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001630 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001631 if (sys_stderr != NULL && sys_stderr != Py_None) {
1632 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1633 } else {
1634 PyObject_Print(value, stderr, Py_PRINT_RAW);
1635 fflush(stderr);
1636 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 PySys_WriteStderr("\n");
1638 exitcode = 1;
1639 }
Tim Peterscf615b52003-04-19 18:47:02 +00001640 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 /* Restore and clear the exception info, in order to properly decref
1642 * the exception, value, and traceback. If we just exit instead,
1643 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1644 * some finalizers from running.
1645 */
1646 PyErr_Restore(exception, value, tb);
1647 PyErr_Clear();
1648 Py_Exit(exitcode);
1649 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001650}
1651
1652void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001653PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1658 handle_system_exit();
1659 }
1660 PyErr_Fetch(&exception, &v, &tb);
1661 if (exception == NULL)
1662 return;
1663 PyErr_NormalizeException(&exception, &v, &tb);
1664 if (tb == NULL) {
1665 tb = Py_None;
1666 Py_INCREF(tb);
1667 }
1668 PyException_SetTraceback(v, tb);
1669 if (exception == NULL)
1670 return;
1671 /* Now we know v != NULL too */
1672 if (set_sys_last_vars) {
1673 PySys_SetObject("last_type", exception);
1674 PySys_SetObject("last_value", v);
1675 PySys_SetObject("last_traceback", tb);
1676 }
1677 hook = PySys_GetObject("excepthook");
1678 if (hook) {
1679 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1680 PyObject *result = PyEval_CallObject(hook, args);
1681 if (result == NULL) {
1682 PyObject *exception2, *v2, *tb2;
1683 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1684 handle_system_exit();
1685 }
1686 PyErr_Fetch(&exception2, &v2, &tb2);
1687 PyErr_NormalizeException(&exception2, &v2, &tb2);
1688 /* It should not be possible for exception2 or v2
1689 to be NULL. However PyErr_Display() can't
1690 tolerate NULLs, so just be safe. */
1691 if (exception2 == NULL) {
1692 exception2 = Py_None;
1693 Py_INCREF(exception2);
1694 }
1695 if (v2 == NULL) {
1696 v2 = Py_None;
1697 Py_INCREF(v2);
1698 }
1699 fflush(stdout);
1700 PySys_WriteStderr("Error in sys.excepthook:\n");
1701 PyErr_Display(exception2, v2, tb2);
1702 PySys_WriteStderr("\nOriginal exception was:\n");
1703 PyErr_Display(exception, v, tb);
1704 Py_DECREF(exception2);
1705 Py_DECREF(v2);
1706 Py_XDECREF(tb2);
1707 }
1708 Py_XDECREF(result);
1709 Py_XDECREF(args);
1710 } else {
1711 PySys_WriteStderr("sys.excepthook is missing\n");
1712 PyErr_Display(exception, v, tb);
1713 }
1714 Py_XDECREF(exception);
1715 Py_XDECREF(v);
1716 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001717}
1718
Benjamin Petersone6528212008-07-15 15:32:09 +00001719static void
1720print_exception(PyObject *f, PyObject *value)
1721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 int err = 0;
1723 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001724 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 if (!PyExceptionInstance_Check(value)) {
1727 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1728 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1729 PyFile_WriteString(" found\n", f);
1730 return;
1731 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 Py_INCREF(value);
1734 fflush(stdout);
1735 type = (PyObject *) Py_TYPE(value);
1736 tb = PyException_GetTraceback(value);
1737 if (tb && tb != Py_None)
1738 err = PyTraceBack_Print(tb, f);
1739 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001740 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 {
1742 PyObject *message;
1743 const char *filename, *text;
1744 int lineno, offset;
1745 if (!parse_syntax_error(value, &message, &filename,
1746 &lineno, &offset, &text))
1747 PyErr_Clear();
1748 else {
1749 char buf[10];
1750 PyFile_WriteString(" File \"", f);
1751 if (filename == NULL)
1752 PyFile_WriteString("<string>", f);
1753 else
1754 PyFile_WriteString(filename, f);
1755 PyFile_WriteString("\", line ", f);
1756 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1757 PyFile_WriteString(buf, f);
1758 PyFile_WriteString("\n", f);
1759 if (text != NULL)
1760 print_error_text(f, offset, text);
1761 Py_DECREF(value);
1762 value = message;
1763 /* Can't be bothered to check all those
1764 PyFile_WriteString() calls */
1765 if (PyErr_Occurred())
1766 err = -1;
1767 }
1768 }
1769 if (err) {
1770 /* Don't do anything else */
1771 }
1772 else {
1773 PyObject* moduleName;
1774 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001775 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 assert(PyExceptionClass_Check(type));
1777 className = PyExceptionClass_Name(type);
1778 if (className != NULL) {
1779 char *dot = strrchr(className, '.');
1780 if (dot != NULL)
1781 className = dot+1;
1782 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001783
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001784 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1786 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001787 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 err = PyFile_WriteString("<unknown>", f);
1789 }
1790 else {
1791 char* modstr = _PyUnicode_AsString(moduleName);
1792 if (modstr && strcmp(modstr, "builtins"))
1793 {
1794 err = PyFile_WriteString(modstr, f);
1795 err += PyFile_WriteString(".", f);
1796 }
1797 Py_DECREF(moduleName);
1798 }
1799 if (err == 0) {
1800 if (className == NULL)
1801 err = PyFile_WriteString("<unknown>", f);
1802 else
1803 err = PyFile_WriteString(className, f);
1804 }
1805 }
1806 if (err == 0 && (value != Py_None)) {
1807 PyObject *s = PyObject_Str(value);
1808 /* only print colon if the str() of the
1809 object is not the empty string
1810 */
1811 if (s == NULL)
1812 err = -1;
1813 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001814 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 err = PyFile_WriteString(": ", f);
1816 if (err == 0)
1817 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1818 Py_XDECREF(s);
1819 }
1820 /* try to write a newline in any case */
1821 err += PyFile_WriteString("\n", f);
1822 Py_XDECREF(tb);
1823 Py_DECREF(value);
1824 /* If an error happened here, don't show it.
1825 XXX This is wrong, but too many callers rely on this behavior. */
1826 if (err != 0)
1827 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001828}
1829
1830static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 "\nThe above exception was the direct cause "
1832 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001833
1834static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 "\nDuring handling of the above exception, "
1836 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001837
1838static void
1839print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 int err = 0, res;
1842 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 if (seen != NULL) {
1845 /* Exception chaining */
1846 if (PySet_Add(seen, value) == -1)
1847 PyErr_Clear();
1848 else if (PyExceptionInstance_Check(value)) {
1849 cause = PyException_GetCause(value);
1850 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001851 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 res = PySet_Contains(seen, cause);
1853 if (res == -1)
1854 PyErr_Clear();
1855 if (res == 0) {
1856 print_exception_recursive(
1857 f, cause, seen);
1858 err |= PyFile_WriteString(
1859 cause_message, f);
1860 }
1861 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001862 else if (context &&
1863 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 res = PySet_Contains(seen, context);
1865 if (res == -1)
1866 PyErr_Clear();
1867 if (res == 0) {
1868 print_exception_recursive(
1869 f, context, seen);
1870 err |= PyFile_WriteString(
1871 context_message, f);
1872 }
1873 }
1874 Py_XDECREF(context);
1875 Py_XDECREF(cause);
1876 }
1877 }
1878 print_exception(f, value);
1879 if (err != 0)
1880 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001881}
1882
Thomas Wouters477c8d52006-05-27 19:21:47 +00001883void
1884PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 PyObject *seen;
1887 PyObject *f = PySys_GetObject("stderr");
Antoine Pitrou24201d42013-10-13 21:53:13 +02001888 if (PyExceptionInstance_Check(value)
1889 && tb != NULL && PyTraceBack_Check(tb)) {
1890 /* Put the traceback on the exception, otherwise it won't get
1891 displayed. See issue #18776. */
1892 PyObject *cur_tb = PyException_GetTraceback(value);
1893 if (cur_tb == NULL)
1894 PyException_SetTraceback(value, tb);
1895 else
1896 Py_DECREF(cur_tb);
1897 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 if (f == Py_None) {
1899 /* pass */
1900 }
1901 else if (f == NULL) {
1902 _PyObject_Dump(value);
1903 fprintf(stderr, "lost sys.stderr\n");
1904 }
1905 else {
1906 /* We choose to ignore seen being possibly NULL, and report
1907 at least the main exception (it could be a MemoryError).
1908 */
1909 seen = PySet_New(NULL);
1910 if (seen == NULL)
1911 PyErr_Clear();
1912 print_exception_recursive(f, value, seen);
1913 Py_XDECREF(seen);
1914 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001915}
1916
Guido van Rossum82598051997-03-05 00:20:32 +00001917PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001918PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 PyObject *ret = NULL;
1922 mod_ty mod;
1923 PyArena *arena = PyArena_New();
1924 if (arena == NULL)
1925 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1928 if (mod != NULL)
1929 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1930 PyArena_Free(arena);
1931 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001932}
1933
1934PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001935PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 PyObject *ret;
1939 mod_ty mod;
1940 PyArena *arena = PyArena_New();
1941 if (arena == NULL)
1942 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1945 flags, NULL, arena);
1946 if (closeit)
1947 fclose(fp);
1948 if (mod == NULL) {
1949 PyArena_Free(arena);
1950 return NULL;
1951 }
1952 ret = run_mod(mod, filename, globals, locals, flags, arena);
1953 PyArena_Free(arena);
1954 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001955}
1956
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001957static void
1958flush_io(void)
1959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 PyObject *f, *r;
1961 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001962 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001963
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 /* Save the current exception */
1965 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 f = PySys_GetObject("stderr");
1968 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001969 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (r)
1971 Py_DECREF(r);
1972 else
1973 PyErr_Clear();
1974 }
1975 f = PySys_GetObject("stdout");
1976 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001977 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 if (r)
1979 Py_DECREF(r);
1980 else
1981 PyErr_Clear();
1982 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001985}
1986
Guido van Rossum82598051997-03-05 00:20:32 +00001987static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001988run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 PyCodeObject *co;
1992 PyObject *v;
1993 co = PyAST_Compile(mod, filename, flags, arena);
1994 if (co == NULL)
1995 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001996 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 Py_DECREF(co);
1998 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001999}
2000
Guido van Rossum82598051997-03-05 00:20:32 +00002001static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002002run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 PyCodeObject *co;
2006 PyObject *v;
2007 long magic;
2008 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 magic = PyMarshal_ReadLongFromFile(fp);
2011 if (magic != PyImport_GetMagicNumber()) {
2012 PyErr_SetString(PyExc_RuntimeError,
2013 "Bad magic number in .pyc file");
2014 return NULL;
2015 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002016 /* Skip mtime and size */
2017 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 (void) PyMarshal_ReadLongFromFile(fp);
2019 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 if (v == NULL || !PyCode_Check(v)) {
2021 Py_XDECREF(v);
2022 PyErr_SetString(PyExc_RuntimeError,
2023 "Bad code object in .pyc file");
2024 return NULL;
2025 }
2026 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002027 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 if (v && flags)
2029 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2030 Py_DECREF(co);
2031 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002032}
2033
Guido van Rossum82598051997-03-05 00:20:32 +00002034PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00002035Py_CompileStringExFlags(const char *str, const char *filename, int start,
2036 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 PyCodeObject *co;
2039 mod_ty mod;
2040 PyArena *arena = PyArena_New();
2041 if (arena == NULL)
2042 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
2045 if (mod == NULL) {
2046 PyArena_Free(arena);
2047 return NULL;
2048 }
2049 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2050 PyObject *result = PyAST_mod2obj(mod);
2051 PyArena_Free(arena);
2052 return result;
2053 }
Georg Brandl8334fd92010-12-04 10:26:46 +00002054 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 PyArena_Free(arena);
2056 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002057}
2058
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002059/* For use in Py_LIMITED_API */
2060#undef Py_CompileString
2061PyObject *
2062PyCompileString(const char *str, const char *filename, int start)
2063{
2064 return Py_CompileStringFlags(str, filename, start, NULL);
2065}
2066
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002067struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002068Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 struct symtable *st;
2071 mod_ty mod;
2072 PyCompilerFlags flags;
2073 PyArena *arena = PyArena_New();
2074 if (arena == NULL)
2075 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 flags.cf_flags = 0;
2078 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
2079 if (mod == NULL) {
2080 PyArena_Free(arena);
2081 return NULL;
2082 }
2083 st = PySymtable_Build(mod, filename, 0);
2084 PyArena_Free(arena);
2085 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002086}
2087
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002088/* Preferred access to parser is through AST. */
2089mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002090PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 mod_ty mod;
2094 PyCompilerFlags localflags;
2095 perrdetail err;
2096 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
2099 &_PyParser_Grammar, start, &err,
2100 &iflags);
2101 if (flags == NULL) {
2102 localflags.cf_flags = 0;
2103 flags = &localflags;
2104 }
2105 if (n) {
2106 flags->cf_flags |= iflags & PyCF_MASK;
2107 mod = PyAST_FromNode(n, flags, filename, arena);
2108 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 }
2110 else {
2111 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002112 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002114 err_free(&err);
2115 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002116}
2117
2118mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00002119PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 int start, char *ps1,
2121 char *ps2, PyCompilerFlags *flags, int *errcode,
2122 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 mod_ty mod;
2125 PyCompilerFlags localflags;
2126 perrdetail err;
2127 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
2130 &_PyParser_Grammar,
2131 start, ps1, ps2, &err, &iflags);
2132 if (flags == NULL) {
2133 localflags.cf_flags = 0;
2134 flags = &localflags;
2135 }
2136 if (n) {
2137 flags->cf_flags |= iflags & PyCF_MASK;
2138 mod = PyAST_FromNode(n, flags, filename, arena);
2139 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 }
2141 else {
2142 err_input(&err);
2143 if (errcode)
2144 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002145 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002147 err_free(&err);
2148 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002149}
2150
Guido van Rossuma110aa61994-08-29 12:50:44 +00002151/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002152
Guido van Rossuma110aa61994-08-29 12:50:44 +00002153node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002154PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 perrdetail err;
2157 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2158 &_PyParser_Grammar,
2159 start, NULL, NULL, &err, flags);
2160 if (n == NULL)
2161 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002162 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002165}
2166
Guido van Rossuma110aa61994-08-29 12:50:44 +00002167/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002168
Guido van Rossuma110aa61994-08-29 12:50:44 +00002169node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002170PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 perrdetail err;
2173 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2174 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;
Tim Petersfe2127d2001-07-16 05:37:24 +00002179}
2180
2181node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002182PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 perrdetail err;
2186 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2187 &_PyParser_Grammar, start, &err, flags);
2188 if (n == NULL)
2189 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002190 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002192}
2193
2194node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002195PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002198}
2199
Guido van Rossum66ebd912003-04-17 16:02:26 +00002200/* May want to move a more generalized form of this to parsetok.c or
2201 even parser modules. */
2202
2203void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002204PyParser_ClearError(perrdetail *err)
2205{
2206 err_free(err);
2207}
2208
2209void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002210PyParser_SetError(perrdetail *err)
2211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002213}
2214
Victor Stinner7f2fee32011-04-05 00:39:01 +02002215static void
2216err_free(perrdetail *err)
2217{
2218 Py_CLEAR(err->filename);
2219}
2220
Guido van Rossuma110aa61994-08-29 12:50:44 +00002221/* Set the error appropriate to the given input error code (see errcode.h) */
2222
2223static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002224err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 PyObject *v, *w, *errtype, *errtext;
2227 PyObject *msg_obj = NULL;
2228 char *msg = NULL;
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002229 int offset = err->offset;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 errtype = PyExc_SyntaxError;
2232 switch (err->error) {
2233 case E_ERROR:
2234 return;
2235 case E_SYNTAX:
2236 errtype = PyExc_IndentationError;
2237 if (err->expected == INDENT)
2238 msg = "expected an indented block";
2239 else if (err->token == INDENT)
2240 msg = "unexpected indent";
2241 else if (err->token == DEDENT)
2242 msg = "unexpected unindent";
2243 else {
2244 errtype = PyExc_SyntaxError;
2245 msg = "invalid syntax";
2246 }
2247 break;
2248 case E_TOKEN:
2249 msg = "invalid token";
2250 break;
2251 case E_EOFS:
2252 msg = "EOF while scanning triple-quoted string literal";
2253 break;
2254 case E_EOLS:
2255 msg = "EOL while scanning string literal";
2256 break;
2257 case E_INTR:
2258 if (!PyErr_Occurred())
2259 PyErr_SetNone(PyExc_KeyboardInterrupt);
2260 goto cleanup;
2261 case E_NOMEM:
2262 PyErr_NoMemory();
2263 goto cleanup;
2264 case E_EOF:
2265 msg = "unexpected EOF while parsing";
2266 break;
2267 case E_TABSPACE:
2268 errtype = PyExc_TabError;
2269 msg = "inconsistent use of tabs and spaces in indentation";
2270 break;
2271 case E_OVERFLOW:
2272 msg = "expression too long";
2273 break;
2274 case E_DEDENT:
2275 errtype = PyExc_IndentationError;
2276 msg = "unindent does not match any outer indentation level";
2277 break;
2278 case E_TOODEEP:
2279 errtype = PyExc_IndentationError;
2280 msg = "too many levels of indentation";
2281 break;
2282 case E_DECODE: {
2283 PyObject *type, *value, *tb;
2284 PyErr_Fetch(&type, &value, &tb);
2285 msg = "unknown decode error";
2286 if (value != NULL)
2287 msg_obj = PyObject_Str(value);
2288 Py_XDECREF(type);
2289 Py_XDECREF(value);
2290 Py_XDECREF(tb);
2291 break;
2292 }
2293 case E_LINECONT:
2294 msg = "unexpected character after line continuation character";
2295 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 case E_IDENTIFIER:
2298 msg = "invalid character in identifier";
2299 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002300 case E_BADSINGLE:
2301 msg = "multiple statements found while compiling a single statement";
2302 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 default:
2304 fprintf(stderr, "error=%d\n", err->error);
2305 msg = "unknown parsing error";
2306 break;
2307 }
2308 /* err->text may not be UTF-8 in case of decoding errors.
2309 Explicitly convert to an object. */
2310 if (!err->text) {
2311 errtext = Py_None;
2312 Py_INCREF(Py_None);
2313 } else {
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002314 errtext = PyUnicode_DecodeUTF8(err->text, err->offset,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 "replace");
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002316 if (errtext != NULL) {
2317 Py_ssize_t len = strlen(err->text);
2318 offset = (int)PyUnicode_GET_LENGTH(errtext);
2319 if (len != err->offset) {
2320 Py_DECREF(errtext);
2321 errtext = PyUnicode_DecodeUTF8(err->text, len,
2322 "replace");
2323 }
2324 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002326 v = Py_BuildValue("(OiiN)", err->filename,
Serhiy Storchaka65fd0592014-01-21 22:26:52 +02002327 err->lineno, offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (v != NULL) {
2329 if (msg_obj)
2330 w = Py_BuildValue("(OO)", msg_obj, v);
2331 else
2332 w = Py_BuildValue("(sO)", msg, v);
2333 } else
2334 w = NULL;
2335 Py_XDECREF(v);
2336 PyErr_SetObject(errtype, w);
2337 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002338cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 Py_XDECREF(msg_obj);
2340 if (err->text != NULL) {
2341 PyObject_FREE(err->text);
2342 err->text = NULL;
2343 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002344}
2345
2346/* Print fatal error message and abort */
2347
2348void
Tim Peters7c321a82002-07-09 02:57:01 +00002349Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002350{
Victor Stinner024e37a2011-03-31 01:31:06 +02002351 const int fd = fileno(stderr);
2352 PyThreadState *tstate;
2353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 fprintf(stderr, "Fatal Python error: %s\n", msg);
2355 fflush(stderr); /* it helps in Windows debug build */
2356 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002357 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002359 else {
2360 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2361 if (tstate != NULL) {
2362 fputc('\n', stderr);
2363 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002364 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002365 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002366 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002367 }
2368
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002369#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 {
2371 size_t len = strlen(msg);
2372 WCHAR* buffer;
2373 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 /* Convert the message to wchar_t. This uses a simple one-to-one
2376 conversion, assuming that the this error message actually uses ASCII
2377 only. If this ceases to be true, we will have to convert. */
2378 buffer = alloca( (len+1) * (sizeof *buffer));
2379 for( i=0; i<=len; ++i)
2380 buffer[i] = msg[i];
2381 OutputDebugStringW(L"Fatal Python error: ");
2382 OutputDebugStringW(buffer);
2383 OutputDebugStringW(L"\n");
2384 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002385#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002387#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002388#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002390}
2391
2392/* Clean up and exit */
2393
Guido van Rossuma110aa61994-08-29 12:50:44 +00002394#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002395#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002396#endif
2397
Collin Winter670e6922007-03-21 02:57:17 +00002398static void (*pyexitfunc)(void) = NULL;
2399/* For the atexit module. */
2400void _Py_PyAtExit(void (*func)(void))
2401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002403}
2404
2405static void
2406call_py_exitfuncs(void)
2407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 if (pyexitfunc == NULL)
2409 return;
Collin Winter670e6922007-03-21 02:57:17 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 (*pyexitfunc)();
2412 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002413}
2414
Antoine Pitrou011bd622009-10-20 21:52:47 +00002415/* Wait until threading._shutdown completes, provided
2416 the threading module was imported in the first place.
2417 The shutdown routine will wait until all non-daemon
2418 "threading" threads have completed. */
2419static void
2420wait_for_thread_shutdown(void)
2421{
2422#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002423 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002424 PyObject *result;
2425 PyThreadState *tstate = PyThreadState_GET();
2426 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2427 "threading");
2428 if (threading == NULL) {
2429 /* threading not imported */
2430 PyErr_Clear();
2431 return;
2432 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002433 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 if (result == NULL) {
2435 PyErr_WriteUnraisable(threading);
2436 }
2437 else {
2438 Py_DECREF(result);
2439 }
2440 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002441#endif
2442}
2443
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002444#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002445static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002446static int nexitfuncs = 0;
2447
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002448int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 if (nexitfuncs >= NEXITFUNCS)
2451 return -1;
2452 exitfuncs[nexitfuncs++] = func;
2453 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002454}
2455
Guido van Rossumcc283f51997-08-05 02:22:03 +00002456static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002457call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 while (nexitfuncs > 0)
2460 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 fflush(stdout);
2463 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002464}
2465
2466void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002467Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002472}
2473
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002474static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002475initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002476{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002477#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002479#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002480#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002482#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002483#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002485#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002487}
2488
Guido van Rossum7433b121997-02-14 19:45:36 +00002489
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002490/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2491 *
2492 * All of the code in this function must only use async-signal-safe functions,
2493 * listed at `man 7 signal` or
2494 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2495 */
2496void
2497_Py_RestoreSignals(void)
2498{
2499#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002501#endif
2502#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002504#endif
2505#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002507#endif
2508}
2509
2510
Guido van Rossum7433b121997-02-14 19:45:36 +00002511/*
2512 * The file descriptor fd is considered ``interactive'' if either
2513 * a) isatty(fd) is TRUE, or
2514 * b) the -i flag was given, and the filename associated with
2515 * the descriptor is NULL or "<stdin>" or "???".
2516 */
2517int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002518Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 if (isatty((int)fileno(fp)))
2521 return 1;
2522 if (!Py_InteractiveFlag)
2523 return 0;
2524 return (filename == NULL) ||
2525 (strcmp(filename, "<stdin>") == 0) ||
2526 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002527}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002528
2529
Tim Petersd08e3822003-04-17 15:24:21 +00002530#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002531#if defined(WIN32) && defined(_MSC_VER)
2532
2533/* Stack checking for Microsoft C */
2534
2535#include <malloc.h>
2536#include <excpt.h>
2537
Fred Drakee8de31c2000-08-31 05:38:39 +00002538/*
2539 * Return non-zero when we run out of memory on the stack; zero otherwise.
2540 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002541int
Fred Drake399739f2000-08-31 05:52:44 +00002542PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 __try {
2545 /* alloca throws a stack overflow exception if there's
2546 not enough space left on the stack */
2547 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2548 return 0;
2549 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2550 EXCEPTION_EXECUTE_HANDLER :
2551 EXCEPTION_CONTINUE_SEARCH) {
2552 int errcode = _resetstkoflw();
2553 if (errcode == 0)
2554 {
2555 Py_FatalError("Could not reset the stack!");
2556 }
2557 }
2558 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002559}
2560
2561#endif /* WIN32 && _MSC_VER */
2562
2563/* Alternate implementations can be added here... */
2564
2565#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002566
2567
2568/* Wrappers around sigaction() or signal(). */
2569
2570PyOS_sighandler_t
2571PyOS_getsig(int sig)
2572{
2573#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 struct sigaction context;
2575 if (sigaction(sig, NULL, &context) == -1)
2576 return SIG_ERR;
2577 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002578#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002580/* Special signal handling for the secure CRT in Visual Studio 2005 */
2581#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 switch (sig) {
2583 /* Only these signals are valid */
2584 case SIGINT:
2585 case SIGILL:
2586 case SIGFPE:
2587 case SIGSEGV:
2588 case SIGTERM:
2589 case SIGBREAK:
2590 case SIGABRT:
2591 break;
2592 /* Don't call signal() with other values or it will assert */
2593 default:
2594 return SIG_ERR;
2595 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002596#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 handler = signal(sig, SIG_IGN);
2598 if (handler != SIG_ERR)
2599 signal(sig, handler);
2600 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002601#endif
2602}
2603
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002604/*
2605 * All of the code in this function must only use async-signal-safe functions,
2606 * listed at `man 7 signal` or
2607 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2608 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002609PyOS_sighandler_t
2610PyOS_setsig(int sig, PyOS_sighandler_t handler)
2611{
2612#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 /* Some code in Modules/signalmodule.c depends on sigaction() being
2614 * used here if HAVE_SIGACTION is defined. Fix that if this code
2615 * changes to invalidate that assumption.
2616 */
2617 struct sigaction context, ocontext;
2618 context.sa_handler = handler;
2619 sigemptyset(&context.sa_mask);
2620 context.sa_flags = 0;
2621 if (sigaction(sig, &context, &ocontext) == -1)
2622 return SIG_ERR;
2623 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002624#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 PyOS_sighandler_t oldhandler;
2626 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002627#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002629#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002631#endif
2632}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002633
2634/* Deprecated C API functions still provided for binary compatiblity */
2635
2636#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002637PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002638PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002641}
2642
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002643#undef PyParser_SimpleParseString
2644PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002645PyParser_SimpleParseString(const char *str, int start)
2646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002648}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002649
2650#undef PyRun_AnyFile
2651PyAPI_FUNC(int)
2652PyRun_AnyFile(FILE *fp, const char *name)
2653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002655}
2656
2657#undef PyRun_AnyFileEx
2658PyAPI_FUNC(int)
2659PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002662}
2663
2664#undef PyRun_AnyFileFlags
2665PyAPI_FUNC(int)
2666PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002669}
2670
2671#undef PyRun_File
2672PyAPI_FUNC(PyObject *)
2673PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002676}
2677
2678#undef PyRun_FileEx
2679PyAPI_FUNC(PyObject *)
2680PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002683}
2684
2685#undef PyRun_FileFlags
2686PyAPI_FUNC(PyObject *)
2687PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002691}
2692
2693#undef PyRun_SimpleFile
2694PyAPI_FUNC(int)
2695PyRun_SimpleFile(FILE *f, const char *p)
2696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002698}
2699
2700#undef PyRun_SimpleFileEx
2701PyAPI_FUNC(int)
2702PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002705}
2706
2707
2708#undef PyRun_String
2709PyAPI_FUNC(PyObject *)
2710PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002713}
2714
2715#undef PyRun_SimpleString
2716PyAPI_FUNC(int)
2717PyRun_SimpleString(const char *s)
2718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002720}
2721
2722#undef Py_CompileString
2723PyAPI_FUNC(PyObject *)
2724Py_CompileString(const char *str, const char *p, int s)
2725{
Georg Brandl8334fd92010-12-04 10:26:46 +00002726 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2727}
2728
2729#undef Py_CompileStringFlags
2730PyAPI_FUNC(PyObject *)
2731Py_CompileStringFlags(const char *str, const char *p, int s,
2732 PyCompilerFlags *flags)
2733{
2734 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002735}
2736
2737#undef PyRun_InteractiveOne
2738PyAPI_FUNC(int)
2739PyRun_InteractiveOne(FILE *f, const char *p)
2740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002742}
2743
2744#undef PyRun_InteractiveLoop
2745PyAPI_FUNC(int)
2746PyRun_InteractiveLoop(FILE *f, const char *p)
2747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002749}
2750
2751#ifdef __cplusplus
2752}
2753#endif