blob: 832df535f8694fc9afa86b24278355b65a8b1c05 [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) {
820 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
821 if (r != (size_t)-1 && r <= PATH_MAX)
822 home = env_home;
823 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 }
826 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000827}
828
Guido van Rossum6135a871995-01-09 17:53:26 +0000829/* Create __main__ module */
830
831static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000832initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyObject *m, *d;
835 m = PyImport_AddModule("__main__");
836 if (m == NULL)
837 Py_FatalError("can't create __main__ module");
838 d = PyModule_GetDict(m);
839 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
840 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000841 if (bimod == NULL) {
842 Py_FatalError("Failed to retrieve builtins module");
843 }
844 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
845 Py_FatalError("Failed to initialize __main__.__builtins__");
846 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 Py_DECREF(bimod);
848 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000849 /* Main is a little special - imp.is_builtin("__main__") will return
850 * False, but BuiltinImporter is still the most appropriate initial
851 * setting for its __loader__ attribute. A more suitable value will
852 * be set if __main__ gets further initialized later in the startup
853 * process.
854 */
855 if (PyDict_GetItemString(d, "__loader__") == NULL) {
856 PyObject *loader = PyObject_GetAttrString(interp->importlib,
857 "BuiltinImporter");
858 if (loader == NULL) {
859 Py_FatalError("Failed to retrieve BuiltinImporter");
860 }
861 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
862 Py_FatalError("Failed to initialize __main__.__loader__");
863 }
864 Py_DECREF(loader);
865 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000866}
867
Victor Stinner793b5312011-04-27 00:24:21 +0200868static int
869initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000870{
871 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000872
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200873 if (Py_FileSystemDefaultEncoding == NULL)
874 {
875 Py_FileSystemDefaultEncoding = get_locale_encoding();
876 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000877 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000878
Victor Stinnere4743092010-10-19 00:05:51 +0000879 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200880 interp->fscodec_initialized = 1;
881 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000882 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000883
884 /* the encoding is mbcs, utf-8 or ascii */
885 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
886 if (!codec) {
887 /* Such error can only occurs in critical situations: no more
888 * memory, import a module of the standard library failed,
889 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200890 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000891 }
Victor Stinner793b5312011-04-27 00:24:21 +0200892 Py_DECREF(codec);
893 interp->fscodec_initialized = 1;
894 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000895}
896
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000897/* Import the site module (not into __main__ though) */
898
899static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000900initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 PyObject *m;
903 m = PyImport_ImportModule("site");
904 if (m == NULL) {
905 PyErr_Print();
906 Py_Finalize();
907 exit(1);
908 }
909 else {
910 Py_DECREF(m);
911 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000912}
913
Antoine Pitrou05608432009-01-09 18:53:14 +0000914static PyObject*
915create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 int fd, int write_mode, char* name,
917 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
920 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000921 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyObject *line_buffering;
923 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200924 _Py_IDENTIFIER(open);
925 _Py_IDENTIFIER(isatty);
926 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200927 _Py_IDENTIFIER(name);
928 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 /* stdin is always opened in buffered mode, first because it shouldn't
931 make a difference in common use cases, second because TextIOWrapper
932 depends on the presence of a read1() method which only exists on
933 buffered streams.
934 */
935 if (Py_UnbufferedStdioFlag && write_mode)
936 buffering = 0;
937 else
938 buffering = -1;
939 if (write_mode)
940 mode = "wb";
941 else
942 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200943 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
944 fd, mode, buffering,
945 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (buf == NULL)
947 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200950 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200951 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 if (raw == NULL)
953 goto error;
954 }
955 else {
956 raw = buf;
957 Py_INCREF(raw);
958 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200961 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200963 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (res == NULL)
965 goto error;
966 isatty = PyObject_IsTrue(res);
967 Py_DECREF(res);
968 if (isatty == -1)
969 goto error;
970 if (isatty || Py_UnbufferedStdioFlag)
971 line_buffering = Py_True;
972 else
973 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000974
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 Py_CLEAR(raw);
976 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000977
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000978#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +0200979 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
980 newlines to "\n".
981 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
982 newline = NULL;
983#else
984 /* sys.stdin: split lines at "\n".
985 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
986 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000987#endif
988
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200989 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
990 buf, encoding, errors,
991 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 Py_CLEAR(buf);
993 if (stream == NULL)
994 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 if (write_mode)
997 mode = "w";
998 else
999 mode = "r";
1000 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001001 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 goto error;
1003 Py_CLEAR(text);
1004 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001005
1006error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 Py_XDECREF(buf);
1008 Py_XDECREF(stream);
1009 Py_XDECREF(text);
1010 Py_XDECREF(raw);
1011 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001012}
1013
Antoine Pitrou11942a52011-11-28 19:08:36 +01001014static int
1015is_valid_fd(int fd)
1016{
1017 int dummy_fd;
1018 if (fd < 0 || !_PyVerify_fd(fd))
1019 return 0;
1020 dummy_fd = dup(fd);
1021 if (dummy_fd < 0)
1022 return 0;
1023 close(dummy_fd);
1024 return 1;
1025}
1026
Georg Brandl1a3284e2007-12-02 09:40:06 +00001027/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001028static int
1029initstdio(void)
1030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 PyObject *iomod = NULL, *wrapper;
1032 PyObject *bimod = NULL;
1033 PyObject *m;
1034 PyObject *std = NULL;
1035 int status = 0, fd;
1036 PyObject * encoding_attr;
1037 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 /* Hack to avoid a nasty recursion issue when Python is invoked
1040 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1041 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1042 goto error;
1043 }
1044 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1047 goto error;
1048 }
1049 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 if (!(bimod = PyImport_ImportModule("builtins"))) {
1052 goto error;
1053 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (!(iomod = PyImport_ImportModule("io"))) {
1056 goto error;
1057 }
1058 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1059 goto error;
1060 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 /* Set builtins.open */
1063 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001064 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 goto error;
1066 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001067 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 encoding = Py_GETENV("PYTHONIOENCODING");
1070 errors = NULL;
1071 if (encoding) {
1072 encoding = strdup(encoding);
1073 errors = strchr(encoding, ':');
1074 if (errors) {
1075 *errors = '\0';
1076 errors++;
1077 }
1078 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 /* Set sys.stdin */
1081 fd = fileno(stdin);
1082 /* Under some conditions stdin, stdout and stderr may not be connected
1083 * and fileno() may point to an invalid file descriptor. For example
1084 * GUI apps don't have valid standard streams by default.
1085 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001086 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 std = Py_None;
1088 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 }
1090 else {
1091 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1092 if (std == NULL)
1093 goto error;
1094 } /* if (fd < 0) */
1095 PySys_SetObject("__stdin__", std);
1096 PySys_SetObject("stdin", std);
1097 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 /* Set sys.stdout */
1100 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001101 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 std = Py_None;
1103 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 }
1105 else {
1106 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1107 if (std == NULL)
1108 goto error;
1109 } /* if (fd < 0) */
1110 PySys_SetObject("__stdout__", std);
1111 PySys_SetObject("stdout", std);
1112 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001113
Guido van Rossum98297ee2007-11-06 21:34:58 +00001114#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 /* Set sys.stderr, replaces the preliminary stderr */
1116 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001117 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 std = Py_None;
1119 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 }
1121 else {
1122 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1123 if (std == NULL)
1124 goto error;
1125 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 /* Same as hack above, pre-import stderr's codec to avoid recursion
1128 when import.c tries to write to stderr in verbose mode. */
1129 encoding_attr = PyObject_GetAttrString(std, "encoding");
1130 if (encoding_attr != NULL) {
1131 const char * encoding;
1132 encoding = _PyUnicode_AsString(encoding_attr);
1133 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001134 PyObject *codec_info = _PyCodec_Lookup(encoding);
1135 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001137 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 }
1139 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PySys_SetObject("__stderr__", std);
1142 PySys_SetObject("stderr", std);
1143 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001144#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001147 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 status = -1;
1149 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (encoding)
1152 free(encoding);
1153 Py_XDECREF(bimod);
1154 Py_XDECREF(iomod);
1155 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001156}
1157
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001158/* Parse input from a file and execute it */
1159
1160int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001161PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 if (filename == NULL)
1165 filename = "???";
1166 if (Py_FdIsInteractive(fp, filename)) {
1167 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1168 if (closeit)
1169 fclose(fp);
1170 return err;
1171 }
1172 else
1173 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001174}
1175
1176int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001177PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 PyObject *v;
1180 int ret;
1181 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (flags == NULL) {
1184 flags = &local_flags;
1185 local_flags.cf_flags = 0;
1186 }
1187 v = PySys_GetObject("ps1");
1188 if (v == NULL) {
1189 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1190 Py_XDECREF(v);
1191 }
1192 v = PySys_GetObject("ps2");
1193 if (v == NULL) {
1194 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1195 Py_XDECREF(v);
1196 }
1197 for (;;) {
1198 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1199 PRINT_TOTAL_REFS();
1200 if (ret == E_EOF)
1201 return 0;
1202 /*
1203 if (ret == E_NOMEM)
1204 return -1;
1205 */
1206 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001207}
1208
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001209/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001210static int PARSER_FLAGS(PyCompilerFlags *flags)
1211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 int parser_flags = 0;
1213 if (!flags)
1214 return 0;
1215 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1216 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1217 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1218 parser_flags |= PyPARSE_IGNORE_COOKIE;
1219 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1220 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1221 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001222}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001223
Thomas Wouters89f507f2006-12-13 04:49:30 +00001224#if 0
1225/* Keep an example of flags with future keyword support. */
1226#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1228 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1229 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1230 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001231#endif
1232
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001233int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001234PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 PyObject *m, *d, *v, *w, *oenc = NULL;
1237 mod_ty mod;
1238 PyArena *arena;
1239 char *ps1 = "", *ps2 = "", *enc = NULL;
1240 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001241 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001244 /* Fetch encoding from sys.stdin if possible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 v = PySys_GetObject("stdin");
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001246 if (v && v != Py_None) {
1247 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1248 if (oenc)
1249 enc = _PyUnicode_AsString(oenc);
1250 if (!enc)
1251 PyErr_Clear();
1252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 }
1254 v = PySys_GetObject("ps1");
1255 if (v != NULL) {
1256 v = PyObject_Str(v);
1257 if (v == NULL)
1258 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001259 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001261 if (ps1 == NULL) {
1262 PyErr_Clear();
1263 ps1 = "";
1264 }
1265 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 }
1267 w = PySys_GetObject("ps2");
1268 if (w != NULL) {
1269 w = PyObject_Str(w);
1270 if (w == NULL)
1271 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001272 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001274 if (ps2 == NULL) {
1275 PyErr_Clear();
1276 ps2 = "";
1277 }
1278 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 }
1280 arena = PyArena_New();
1281 if (arena == NULL) {
1282 Py_XDECREF(v);
1283 Py_XDECREF(w);
1284 Py_XDECREF(oenc);
1285 return -1;
1286 }
1287 mod = PyParser_ASTFromFile(fp, filename, enc,
1288 Py_single_input, ps1, ps2,
1289 flags, &errcode, arena);
1290 Py_XDECREF(v);
1291 Py_XDECREF(w);
1292 Py_XDECREF(oenc);
1293 if (mod == NULL) {
1294 PyArena_Free(arena);
1295 if (errcode == E_EOF) {
1296 PyErr_Clear();
1297 return E_EOF;
1298 }
1299 PyErr_Print();
1300 return -1;
1301 }
1302 m = PyImport_AddModule("__main__");
1303 if (m == NULL) {
1304 PyArena_Free(arena);
1305 return -1;
1306 }
1307 d = PyModule_GetDict(m);
1308 v = run_mod(mod, filename, d, d, flags, arena);
1309 PyArena_Free(arena);
1310 flush_io();
1311 if (v == NULL) {
1312 PyErr_Print();
1313 return -1;
1314 }
1315 Py_DECREF(v);
1316 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001317}
1318
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001319/* Check whether a file maybe a pyc file: Look at the extension,
1320 the file type, and, if we may close it, at the first few bytes. */
1321
1322static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001323maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1326 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 /* Only look into the file if we are allowed to close it, since
1329 it then should also be seekable. */
1330 if (closeit) {
1331 /* Read only two bytes of the magic. If the file was opened in
1332 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1333 be read as they are on disk. */
1334 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1335 unsigned char buf[2];
1336 /* Mess: In case of -x, the stream is NOT at its start now,
1337 and ungetc() was used to push back the first newline,
1338 which makes the current stream position formally undefined,
1339 and a x-platform nightmare.
1340 Unfortunately, we have no direct way to know whether -x
1341 was specified. So we use a terrible hack: if the current
1342 stream position is not 0, we assume -x was specified, and
1343 give up. Bug 132850 on SourceForge spells out the
1344 hopelessness of trying anything else (fseek and ftell
1345 don't work predictably x-platform for text-mode files).
1346 */
1347 int ispyc = 0;
1348 if (ftell(fp) == 0) {
1349 if (fread(buf, 1, 2, fp) == 2 &&
1350 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1351 ispyc = 1;
1352 rewind(fp);
1353 }
1354 return ispyc;
1355 }
1356 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001357}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001358
Guido van Rossum0df002c2000-08-27 19:21:52 +00001359int
Nick Coghlanceda83c2012-07-15 23:18:08 +10001360static set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001361{
1362 PyInterpreterState *interp;
1363 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001364 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001365 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001366
1367 filename_obj = PyUnicode_DecodeFSDefault(filename);
1368 if (filename_obj == NULL)
1369 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001370 /* Get current thread state and interpreter pointer */
1371 tstate = PyThreadState_GET();
1372 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001373 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1374 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001375 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001376 return -1;
1377 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001378 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001379 Py_DECREF(loader_type);
1380 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001381 return -1;
1382 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001383 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1384 result = -1;
1385 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001386 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001387 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001388}
1389
1390int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001391PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 PyObject *m, *d, *v;
1395 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001396 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001397 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 m = PyImport_AddModule("__main__");
1400 if (m == NULL)
1401 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001402 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 d = PyModule_GetDict(m);
1404 if (PyDict_GetItemString(d, "__file__") == NULL) {
1405 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001406 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001408 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1410 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001411 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001413 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1414 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001415 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001416 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 set_file_name = 1;
1418 Py_DECREF(f);
1419 }
1420 len = strlen(filename);
1421 ext = filename + len - (len > 4 ? 4 : 0);
1422 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001423 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 /* Try to run a pyc file. First, re-open in binary */
1425 if (closeit)
1426 fclose(fp);
Christian Heimes04ac4c12012-09-11 15:47:28 +02001427 if ((pyc_fp = fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 goto done;
1430 }
1431 /* Turn on optimization if a .pyo file is given */
1432 if (strcmp(ext, ".pyo") == 0)
1433 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001434
1435 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1436 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1437 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001438 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001439 goto done;
1440 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001441 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1442 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001444 /* When running from stdin, leave __main__.__loader__ alone */
1445 if (strcmp(filename, "<stdin>") != 0 &&
1446 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1447 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1448 ret = -1;
1449 goto done;
1450 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1452 closeit, flags);
1453 }
1454 flush_io();
1455 if (v == NULL) {
1456 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 goto done;
1458 }
1459 Py_DECREF(v);
1460 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001461 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1463 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001464 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001466}
1467
1468int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001469PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 PyObject *m, *d, *v;
1472 m = PyImport_AddModule("__main__");
1473 if (m == NULL)
1474 return -1;
1475 d = PyModule_GetDict(m);
1476 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1477 if (v == NULL) {
1478 PyErr_Print();
1479 return -1;
1480 }
1481 Py_DECREF(v);
1482 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001483}
1484
Barry Warsaw035574d1997-08-29 22:07:17 +00001485static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001486parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 long hold;
1490 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001491 _Py_IDENTIFIER(msg);
1492 _Py_IDENTIFIER(filename);
1493 _Py_IDENTIFIER(lineno);
1494 _Py_IDENTIFIER(offset);
1495 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001496
Benjamin Peterson80d50422012-04-03 00:30:38 -04001497 *message = NULL;
1498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001500 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001501 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001503
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001504 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001505 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001507 if (v == Py_None) {
1508 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001510 }
1511 else {
1512 *filename = _PyUnicode_AsString(v);
1513 Py_DECREF(v);
1514 if (!*filename)
1515 goto finally;
1516 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001517
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001518 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001519 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 goto finally;
1521 hold = PyLong_AsLong(v);
1522 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (hold < 0 && PyErr_Occurred())
1524 goto finally;
1525 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001526
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001527 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001528 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 goto finally;
1530 if (v == Py_None) {
1531 *offset = -1;
1532 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 } else {
1534 hold = PyLong_AsLong(v);
1535 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 if (hold < 0 && PyErr_Occurred())
1537 goto finally;
1538 *offset = (int)hold;
1539 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001540
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001541 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001542 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001544 if (v == Py_None) {
1545 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001547 }
1548 else {
1549 *text = _PyUnicode_AsString(v);
1550 Py_DECREF(v);
1551 if (!*text)
1552 goto finally;
1553 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001555
1556finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001557 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001559}
1560
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001561void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001562PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001565}
1566
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001567static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001568print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 char *nl;
1571 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001572 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1573 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 for (;;) {
1575 nl = strchr(text, '\n');
1576 if (nl == NULL || nl-text >= offset)
1577 break;
1578 offset -= (int)(nl+1-text);
1579 text = nl+1;
1580 }
1581 while (*text == ' ' || *text == '\t') {
1582 text++;
1583 offset--;
1584 }
1585 }
1586 PyFile_WriteString(" ", f);
1587 PyFile_WriteString(text, f);
1588 if (*text == '\0' || text[strlen(text)-1] != '\n')
1589 PyFile_WriteString("\n", f);
1590 if (offset == -1)
1591 return;
1592 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001593 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001596}
1597
Guido van Rossum66e8e862001-03-23 17:54:43 +00001598static void
1599handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 PyObject *exception, *value, *tb;
1602 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 if (Py_InspectFlag)
1605 /* Don't exit if -i flag was given. This flag is set to 0
1606 * when entering interactive mode for inspecting. */
1607 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 PyErr_Fetch(&exception, &value, &tb);
1610 fflush(stdout);
1611 if (value == NULL || value == Py_None)
1612 goto done;
1613 if (PyExceptionInstance_Check(value)) {
1614 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001615 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001616 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 if (code) {
1618 Py_DECREF(value);
1619 value = code;
1620 if (value == Py_None)
1621 goto done;
1622 }
1623 /* If we failed to dig out the 'code' attribute,
1624 just let the else clause below print the error. */
1625 }
1626 if (PyLong_Check(value))
1627 exitcode = (int)PyLong_AsLong(value);
1628 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001629 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001630 if (sys_stderr != NULL && sys_stderr != Py_None) {
1631 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1632 } else {
1633 PyObject_Print(value, stderr, Py_PRINT_RAW);
1634 fflush(stderr);
1635 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 PySys_WriteStderr("\n");
1637 exitcode = 1;
1638 }
Tim Peterscf615b52003-04-19 18:47:02 +00001639 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 /* Restore and clear the exception info, in order to properly decref
1641 * the exception, value, and traceback. If we just exit instead,
1642 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1643 * some finalizers from running.
1644 */
1645 PyErr_Restore(exception, value, tb);
1646 PyErr_Clear();
1647 Py_Exit(exitcode);
1648 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001649}
1650
1651void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001652PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1657 handle_system_exit();
1658 }
1659 PyErr_Fetch(&exception, &v, &tb);
1660 if (exception == NULL)
1661 return;
1662 PyErr_NormalizeException(&exception, &v, &tb);
1663 if (tb == NULL) {
1664 tb = Py_None;
1665 Py_INCREF(tb);
1666 }
1667 PyException_SetTraceback(v, tb);
1668 if (exception == NULL)
1669 return;
1670 /* Now we know v != NULL too */
1671 if (set_sys_last_vars) {
1672 PySys_SetObject("last_type", exception);
1673 PySys_SetObject("last_value", v);
1674 PySys_SetObject("last_traceback", tb);
1675 }
1676 hook = PySys_GetObject("excepthook");
1677 if (hook) {
1678 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1679 PyObject *result = PyEval_CallObject(hook, args);
1680 if (result == NULL) {
1681 PyObject *exception2, *v2, *tb2;
1682 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1683 handle_system_exit();
1684 }
1685 PyErr_Fetch(&exception2, &v2, &tb2);
1686 PyErr_NormalizeException(&exception2, &v2, &tb2);
1687 /* It should not be possible for exception2 or v2
1688 to be NULL. However PyErr_Display() can't
1689 tolerate NULLs, so just be safe. */
1690 if (exception2 == NULL) {
1691 exception2 = Py_None;
1692 Py_INCREF(exception2);
1693 }
1694 if (v2 == NULL) {
1695 v2 = Py_None;
1696 Py_INCREF(v2);
1697 }
1698 fflush(stdout);
1699 PySys_WriteStderr("Error in sys.excepthook:\n");
1700 PyErr_Display(exception2, v2, tb2);
1701 PySys_WriteStderr("\nOriginal exception was:\n");
1702 PyErr_Display(exception, v, tb);
1703 Py_DECREF(exception2);
1704 Py_DECREF(v2);
1705 Py_XDECREF(tb2);
1706 }
1707 Py_XDECREF(result);
1708 Py_XDECREF(args);
1709 } else {
1710 PySys_WriteStderr("sys.excepthook is missing\n");
1711 PyErr_Display(exception, v, tb);
1712 }
1713 Py_XDECREF(exception);
1714 Py_XDECREF(v);
1715 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001716}
1717
Benjamin Petersone6528212008-07-15 15:32:09 +00001718static void
1719print_exception(PyObject *f, PyObject *value)
1720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 int err = 0;
1722 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001723 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 if (!PyExceptionInstance_Check(value)) {
1726 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1727 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1728 PyFile_WriteString(" found\n", f);
1729 return;
1730 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 Py_INCREF(value);
1733 fflush(stdout);
1734 type = (PyObject *) Py_TYPE(value);
1735 tb = PyException_GetTraceback(value);
1736 if (tb && tb != Py_None)
1737 err = PyTraceBack_Print(tb, f);
1738 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001739 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 {
1741 PyObject *message;
1742 const char *filename, *text;
1743 int lineno, offset;
1744 if (!parse_syntax_error(value, &message, &filename,
1745 &lineno, &offset, &text))
1746 PyErr_Clear();
1747 else {
1748 char buf[10];
1749 PyFile_WriteString(" File \"", f);
1750 if (filename == NULL)
1751 PyFile_WriteString("<string>", f);
1752 else
1753 PyFile_WriteString(filename, f);
1754 PyFile_WriteString("\", line ", f);
1755 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1756 PyFile_WriteString(buf, f);
1757 PyFile_WriteString("\n", f);
1758 if (text != NULL)
1759 print_error_text(f, offset, text);
1760 Py_DECREF(value);
1761 value = message;
1762 /* Can't be bothered to check all those
1763 PyFile_WriteString() calls */
1764 if (PyErr_Occurred())
1765 err = -1;
1766 }
1767 }
1768 if (err) {
1769 /* Don't do anything else */
1770 }
1771 else {
1772 PyObject* moduleName;
1773 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001774 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 assert(PyExceptionClass_Check(type));
1776 className = PyExceptionClass_Name(type);
1777 if (className != NULL) {
1778 char *dot = strrchr(className, '.');
1779 if (dot != NULL)
1780 className = dot+1;
1781 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001782
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001783 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1785 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001786 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 err = PyFile_WriteString("<unknown>", f);
1788 }
1789 else {
1790 char* modstr = _PyUnicode_AsString(moduleName);
1791 if (modstr && strcmp(modstr, "builtins"))
1792 {
1793 err = PyFile_WriteString(modstr, f);
1794 err += PyFile_WriteString(".", f);
1795 }
1796 Py_DECREF(moduleName);
1797 }
1798 if (err == 0) {
1799 if (className == NULL)
1800 err = PyFile_WriteString("<unknown>", f);
1801 else
1802 err = PyFile_WriteString(className, f);
1803 }
1804 }
1805 if (err == 0 && (value != Py_None)) {
1806 PyObject *s = PyObject_Str(value);
1807 /* only print colon if the str() of the
1808 object is not the empty string
1809 */
1810 if (s == NULL)
1811 err = -1;
1812 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001813 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 err = PyFile_WriteString(": ", f);
1815 if (err == 0)
1816 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1817 Py_XDECREF(s);
1818 }
1819 /* try to write a newline in any case */
1820 err += PyFile_WriteString("\n", f);
1821 Py_XDECREF(tb);
1822 Py_DECREF(value);
1823 /* If an error happened here, don't show it.
1824 XXX This is wrong, but too many callers rely on this behavior. */
1825 if (err != 0)
1826 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001827}
1828
1829static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 "\nThe above exception was the direct cause "
1831 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001832
1833static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 "\nDuring handling of the above exception, "
1835 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001836
1837static void
1838print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 int err = 0, res;
1841 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 if (seen != NULL) {
1844 /* Exception chaining */
1845 if (PySet_Add(seen, value) == -1)
1846 PyErr_Clear();
1847 else if (PyExceptionInstance_Check(value)) {
1848 cause = PyException_GetCause(value);
1849 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001850 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 res = PySet_Contains(seen, cause);
1852 if (res == -1)
1853 PyErr_Clear();
1854 if (res == 0) {
1855 print_exception_recursive(
1856 f, cause, seen);
1857 err |= PyFile_WriteString(
1858 cause_message, f);
1859 }
1860 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001861 else if (context &&
1862 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 res = PySet_Contains(seen, context);
1864 if (res == -1)
1865 PyErr_Clear();
1866 if (res == 0) {
1867 print_exception_recursive(
1868 f, context, seen);
1869 err |= PyFile_WriteString(
1870 context_message, f);
1871 }
1872 }
1873 Py_XDECREF(context);
1874 Py_XDECREF(cause);
1875 }
1876 }
1877 print_exception(f, value);
1878 if (err != 0)
1879 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001880}
1881
Thomas Wouters477c8d52006-05-27 19:21:47 +00001882void
1883PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 PyObject *seen;
1886 PyObject *f = PySys_GetObject("stderr");
Antoine Pitrou24201d42013-10-13 21:53:13 +02001887 if (PyExceptionInstance_Check(value)
1888 && tb != NULL && PyTraceBack_Check(tb)) {
1889 /* Put the traceback on the exception, otherwise it won't get
1890 displayed. See issue #18776. */
1891 PyObject *cur_tb = PyException_GetTraceback(value);
1892 if (cur_tb == NULL)
1893 PyException_SetTraceback(value, tb);
1894 else
1895 Py_DECREF(cur_tb);
1896 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 if (f == Py_None) {
1898 /* pass */
1899 }
1900 else if (f == NULL) {
1901 _PyObject_Dump(value);
1902 fprintf(stderr, "lost sys.stderr\n");
1903 }
1904 else {
1905 /* We choose to ignore seen being possibly NULL, and report
1906 at least the main exception (it could be a MemoryError).
1907 */
1908 seen = PySet_New(NULL);
1909 if (seen == NULL)
1910 PyErr_Clear();
1911 print_exception_recursive(f, value, seen);
1912 Py_XDECREF(seen);
1913 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001914}
1915
Guido van Rossum82598051997-03-05 00:20:32 +00001916PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001917PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 PyObject *ret = NULL;
1921 mod_ty mod;
1922 PyArena *arena = PyArena_New();
1923 if (arena == NULL)
1924 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1927 if (mod != NULL)
1928 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1929 PyArena_Free(arena);
1930 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001931}
1932
1933PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001934PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 PyObject *ret;
1938 mod_ty mod;
1939 PyArena *arena = PyArena_New();
1940 if (arena == NULL)
1941 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001943 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1944 flags, NULL, arena);
1945 if (closeit)
1946 fclose(fp);
1947 if (mod == NULL) {
1948 PyArena_Free(arena);
1949 return NULL;
1950 }
1951 ret = run_mod(mod, filename, globals, locals, flags, arena);
1952 PyArena_Free(arena);
1953 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001954}
1955
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001956static void
1957flush_io(void)
1958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 PyObject *f, *r;
1960 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001961 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 /* Save the current exception */
1964 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 f = PySys_GetObject("stderr");
1967 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001968 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 if (r)
1970 Py_DECREF(r);
1971 else
1972 PyErr_Clear();
1973 }
1974 f = PySys_GetObject("stdout");
1975 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001976 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 if (r)
1978 Py_DECREF(r);
1979 else
1980 PyErr_Clear();
1981 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001984}
1985
Guido van Rossum82598051997-03-05 00:20:32 +00001986static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001987run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 PyCodeObject *co;
1991 PyObject *v;
1992 co = PyAST_Compile(mod, filename, flags, arena);
1993 if (co == NULL)
1994 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001995 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 Py_DECREF(co);
1997 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001998}
1999
Guido van Rossum82598051997-03-05 00:20:32 +00002000static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002001run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 PyCodeObject *co;
2005 PyObject *v;
2006 long magic;
2007 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 magic = PyMarshal_ReadLongFromFile(fp);
2010 if (magic != PyImport_GetMagicNumber()) {
2011 PyErr_SetString(PyExc_RuntimeError,
2012 "Bad magic number in .pyc file");
2013 return NULL;
2014 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002015 /* Skip mtime and size */
2016 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 (void) PyMarshal_ReadLongFromFile(fp);
2018 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 if (v == NULL || !PyCode_Check(v)) {
2020 Py_XDECREF(v);
2021 PyErr_SetString(PyExc_RuntimeError,
2022 "Bad code object in .pyc file");
2023 return NULL;
2024 }
2025 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002026 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 if (v && flags)
2028 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2029 Py_DECREF(co);
2030 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002031}
2032
Guido van Rossum82598051997-03-05 00:20:32 +00002033PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00002034Py_CompileStringExFlags(const char *str, const char *filename, int start,
2035 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 PyCodeObject *co;
2038 mod_ty mod;
2039 PyArena *arena = PyArena_New();
2040 if (arena == NULL)
2041 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002042
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
2044 if (mod == NULL) {
2045 PyArena_Free(arena);
2046 return NULL;
2047 }
2048 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2049 PyObject *result = PyAST_mod2obj(mod);
2050 PyArena_Free(arena);
2051 return result;
2052 }
Georg Brandl8334fd92010-12-04 10:26:46 +00002053 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 PyArena_Free(arena);
2055 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002056}
2057
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002058/* For use in Py_LIMITED_API */
2059#undef Py_CompileString
2060PyObject *
2061PyCompileString(const char *str, const char *filename, int start)
2062{
2063 return Py_CompileStringFlags(str, filename, start, NULL);
2064}
2065
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002066struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002067Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 struct symtable *st;
2070 mod_ty mod;
2071 PyCompilerFlags flags;
2072 PyArena *arena = PyArena_New();
2073 if (arena == NULL)
2074 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 flags.cf_flags = 0;
2077 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
2078 if (mod == NULL) {
2079 PyArena_Free(arena);
2080 return NULL;
2081 }
2082 st = PySymtable_Build(mod, filename, 0);
2083 PyArena_Free(arena);
2084 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002085}
2086
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002087/* Preferred access to parser is through AST. */
2088mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002089PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 mod_ty mod;
2093 PyCompilerFlags localflags;
2094 perrdetail err;
2095 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
2098 &_PyParser_Grammar, start, &err,
2099 &iflags);
2100 if (flags == NULL) {
2101 localflags.cf_flags = 0;
2102 flags = &localflags;
2103 }
2104 if (n) {
2105 flags->cf_flags |= iflags & PyCF_MASK;
2106 mod = PyAST_FromNode(n, flags, filename, arena);
2107 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 }
2109 else {
2110 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002111 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002113 err_free(&err);
2114 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002115}
2116
2117mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00002118PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 int start, char *ps1,
2120 char *ps2, PyCompilerFlags *flags, int *errcode,
2121 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 mod_ty mod;
2124 PyCompilerFlags localflags;
2125 perrdetail err;
2126 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
2129 &_PyParser_Grammar,
2130 start, ps1, ps2, &err, &iflags);
2131 if (flags == NULL) {
2132 localflags.cf_flags = 0;
2133 flags = &localflags;
2134 }
2135 if (n) {
2136 flags->cf_flags |= iflags & PyCF_MASK;
2137 mod = PyAST_FromNode(n, flags, filename, arena);
2138 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 }
2140 else {
2141 err_input(&err);
2142 if (errcode)
2143 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002144 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002146 err_free(&err);
2147 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002148}
2149
Guido van Rossuma110aa61994-08-29 12:50:44 +00002150/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002151
Guido van Rossuma110aa61994-08-29 12:50:44 +00002152node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002153PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 perrdetail err;
2156 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2157 &_PyParser_Grammar,
2158 start, NULL, NULL, &err, flags);
2159 if (n == NULL)
2160 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002161 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002164}
2165
Guido van Rossuma110aa61994-08-29 12:50:44 +00002166/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002167
Guido van Rossuma110aa61994-08-29 12:50:44 +00002168node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002169PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 perrdetail err;
2172 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2173 start, &err, flags);
2174 if (n == NULL)
2175 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002176 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002178}
2179
2180node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002181PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 perrdetail err;
2185 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2186 &_PyParser_Grammar, start, &err, flags);
2187 if (n == NULL)
2188 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002189 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002191}
2192
2193node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002194PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002197}
2198
Guido van Rossum66ebd912003-04-17 16:02:26 +00002199/* May want to move a more generalized form of this to parsetok.c or
2200 even parser modules. */
2201
2202void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002203PyParser_ClearError(perrdetail *err)
2204{
2205 err_free(err);
2206}
2207
2208void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002209PyParser_SetError(perrdetail *err)
2210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002212}
2213
Victor Stinner7f2fee32011-04-05 00:39:01 +02002214static void
2215err_free(perrdetail *err)
2216{
2217 Py_CLEAR(err->filename);
2218}
2219
Guido van Rossuma110aa61994-08-29 12:50:44 +00002220/* Set the error appropriate to the given input error code (see errcode.h) */
2221
2222static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002223err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 PyObject *v, *w, *errtype, *errtext;
2226 PyObject *msg_obj = NULL;
2227 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 errtype = PyExc_SyntaxError;
2230 switch (err->error) {
2231 case E_ERROR:
2232 return;
2233 case E_SYNTAX:
2234 errtype = PyExc_IndentationError;
2235 if (err->expected == INDENT)
2236 msg = "expected an indented block";
2237 else if (err->token == INDENT)
2238 msg = "unexpected indent";
2239 else if (err->token == DEDENT)
2240 msg = "unexpected unindent";
2241 else {
2242 errtype = PyExc_SyntaxError;
2243 msg = "invalid syntax";
2244 }
2245 break;
2246 case E_TOKEN:
2247 msg = "invalid token";
2248 break;
2249 case E_EOFS:
2250 msg = "EOF while scanning triple-quoted string literal";
2251 break;
2252 case E_EOLS:
2253 msg = "EOL while scanning string literal";
2254 break;
2255 case E_INTR:
2256 if (!PyErr_Occurred())
2257 PyErr_SetNone(PyExc_KeyboardInterrupt);
2258 goto cleanup;
2259 case E_NOMEM:
2260 PyErr_NoMemory();
2261 goto cleanup;
2262 case E_EOF:
2263 msg = "unexpected EOF while parsing";
2264 break;
2265 case E_TABSPACE:
2266 errtype = PyExc_TabError;
2267 msg = "inconsistent use of tabs and spaces in indentation";
2268 break;
2269 case E_OVERFLOW:
2270 msg = "expression too long";
2271 break;
2272 case E_DEDENT:
2273 errtype = PyExc_IndentationError;
2274 msg = "unindent does not match any outer indentation level";
2275 break;
2276 case E_TOODEEP:
2277 errtype = PyExc_IndentationError;
2278 msg = "too many levels of indentation";
2279 break;
2280 case E_DECODE: {
2281 PyObject *type, *value, *tb;
2282 PyErr_Fetch(&type, &value, &tb);
2283 msg = "unknown decode error";
2284 if (value != NULL)
2285 msg_obj = PyObject_Str(value);
2286 Py_XDECREF(type);
2287 Py_XDECREF(value);
2288 Py_XDECREF(tb);
2289 break;
2290 }
2291 case E_LINECONT:
2292 msg = "unexpected character after line continuation character";
2293 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 case E_IDENTIFIER:
2296 msg = "invalid character in identifier";
2297 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002298 case E_BADSINGLE:
2299 msg = "multiple statements found while compiling a single statement";
2300 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 default:
2302 fprintf(stderr, "error=%d\n", err->error);
2303 msg = "unknown parsing error";
2304 break;
2305 }
2306 /* err->text may not be UTF-8 in case of decoding errors.
2307 Explicitly convert to an object. */
2308 if (!err->text) {
2309 errtext = Py_None;
2310 Py_INCREF(Py_None);
2311 } else {
2312 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2313 "replace");
2314 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002315 v = Py_BuildValue("(OiiN)", err->filename,
2316 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 if (v != NULL) {
2318 if (msg_obj)
2319 w = Py_BuildValue("(OO)", msg_obj, v);
2320 else
2321 w = Py_BuildValue("(sO)", msg, v);
2322 } else
2323 w = NULL;
2324 Py_XDECREF(v);
2325 PyErr_SetObject(errtype, w);
2326 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002327cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 Py_XDECREF(msg_obj);
2329 if (err->text != NULL) {
2330 PyObject_FREE(err->text);
2331 err->text = NULL;
2332 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002333}
2334
2335/* Print fatal error message and abort */
2336
2337void
Tim Peters7c321a82002-07-09 02:57:01 +00002338Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002339{
Victor Stinner024e37a2011-03-31 01:31:06 +02002340 const int fd = fileno(stderr);
2341 PyThreadState *tstate;
2342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 fprintf(stderr, "Fatal Python error: %s\n", msg);
2344 fflush(stderr); /* it helps in Windows debug build */
2345 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002346 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002348 else {
2349 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2350 if (tstate != NULL) {
2351 fputc('\n', stderr);
2352 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002353 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002354 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002355 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002356 }
2357
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002358#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 {
2360 size_t len = strlen(msg);
2361 WCHAR* buffer;
2362 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 /* Convert the message to wchar_t. This uses a simple one-to-one
2365 conversion, assuming that the this error message actually uses ASCII
2366 only. If this ceases to be true, we will have to convert. */
2367 buffer = alloca( (len+1) * (sizeof *buffer));
2368 for( i=0; i<=len; ++i)
2369 buffer[i] = msg[i];
2370 OutputDebugStringW(L"Fatal Python error: ");
2371 OutputDebugStringW(buffer);
2372 OutputDebugStringW(L"\n");
2373 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002374#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002376#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002377#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002379}
2380
2381/* Clean up and exit */
2382
Guido van Rossuma110aa61994-08-29 12:50:44 +00002383#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002384#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002385#endif
2386
Collin Winter670e6922007-03-21 02:57:17 +00002387static void (*pyexitfunc)(void) = NULL;
2388/* For the atexit module. */
2389void _Py_PyAtExit(void (*func)(void))
2390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002392}
2393
2394static void
2395call_py_exitfuncs(void)
2396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 if (pyexitfunc == NULL)
2398 return;
Collin Winter670e6922007-03-21 02:57:17 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 (*pyexitfunc)();
2401 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002402}
2403
Antoine Pitrou011bd622009-10-20 21:52:47 +00002404/* Wait until threading._shutdown completes, provided
2405 the threading module was imported in the first place.
2406 The shutdown routine will wait until all non-daemon
2407 "threading" threads have completed. */
2408static void
2409wait_for_thread_shutdown(void)
2410{
2411#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002412 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 PyObject *result;
2414 PyThreadState *tstate = PyThreadState_GET();
2415 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2416 "threading");
2417 if (threading == NULL) {
2418 /* threading not imported */
2419 PyErr_Clear();
2420 return;
2421 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002422 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 if (result == NULL) {
2424 PyErr_WriteUnraisable(threading);
2425 }
2426 else {
2427 Py_DECREF(result);
2428 }
2429 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002430#endif
2431}
2432
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002433#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002434static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002435static int nexitfuncs = 0;
2436
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002437int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 if (nexitfuncs >= NEXITFUNCS)
2440 return -1;
2441 exitfuncs[nexitfuncs++] = func;
2442 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002443}
2444
Guido van Rossumcc283f51997-08-05 02:22:03 +00002445static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002446call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 while (nexitfuncs > 0)
2449 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 fflush(stdout);
2452 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002453}
2454
2455void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002456Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002461}
2462
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002463static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002464initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002465{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002466#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002468#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002469#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002471#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002472#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002474#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002476}
2477
Guido van Rossum7433b121997-02-14 19:45:36 +00002478
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002479/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2480 *
2481 * All of the code in this function must only use async-signal-safe functions,
2482 * listed at `man 7 signal` or
2483 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2484 */
2485void
2486_Py_RestoreSignals(void)
2487{
2488#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002490#endif
2491#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002493#endif
2494#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002496#endif
2497}
2498
2499
Guido van Rossum7433b121997-02-14 19:45:36 +00002500/*
2501 * The file descriptor fd is considered ``interactive'' if either
2502 * a) isatty(fd) is TRUE, or
2503 * b) the -i flag was given, and the filename associated with
2504 * the descriptor is NULL or "<stdin>" or "???".
2505 */
2506int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002507Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 if (isatty((int)fileno(fp)))
2510 return 1;
2511 if (!Py_InteractiveFlag)
2512 return 0;
2513 return (filename == NULL) ||
2514 (strcmp(filename, "<stdin>") == 0) ||
2515 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002516}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002517
2518
Tim Petersd08e3822003-04-17 15:24:21 +00002519#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002520#if defined(WIN32) && defined(_MSC_VER)
2521
2522/* Stack checking for Microsoft C */
2523
2524#include <malloc.h>
2525#include <excpt.h>
2526
Fred Drakee8de31c2000-08-31 05:38:39 +00002527/*
2528 * Return non-zero when we run out of memory on the stack; zero otherwise.
2529 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002530int
Fred Drake399739f2000-08-31 05:52:44 +00002531PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002533 __try {
2534 /* alloca throws a stack overflow exception if there's
2535 not enough space left on the stack */
2536 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2537 return 0;
2538 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2539 EXCEPTION_EXECUTE_HANDLER :
2540 EXCEPTION_CONTINUE_SEARCH) {
2541 int errcode = _resetstkoflw();
2542 if (errcode == 0)
2543 {
2544 Py_FatalError("Could not reset the stack!");
2545 }
2546 }
2547 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002548}
2549
2550#endif /* WIN32 && _MSC_VER */
2551
2552/* Alternate implementations can be added here... */
2553
2554#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002555
2556
2557/* Wrappers around sigaction() or signal(). */
2558
2559PyOS_sighandler_t
2560PyOS_getsig(int sig)
2561{
2562#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 struct sigaction context;
2564 if (sigaction(sig, NULL, &context) == -1)
2565 return SIG_ERR;
2566 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002567#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002569/* Special signal handling for the secure CRT in Visual Studio 2005 */
2570#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 switch (sig) {
2572 /* Only these signals are valid */
2573 case SIGINT:
2574 case SIGILL:
2575 case SIGFPE:
2576 case SIGSEGV:
2577 case SIGTERM:
2578 case SIGBREAK:
2579 case SIGABRT:
2580 break;
2581 /* Don't call signal() with other values or it will assert */
2582 default:
2583 return SIG_ERR;
2584 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002585#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 handler = signal(sig, SIG_IGN);
2587 if (handler != SIG_ERR)
2588 signal(sig, handler);
2589 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002590#endif
2591}
2592
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002593/*
2594 * All of the code in this function must only use async-signal-safe functions,
2595 * listed at `man 7 signal` or
2596 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2597 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002598PyOS_sighandler_t
2599PyOS_setsig(int sig, PyOS_sighandler_t handler)
2600{
2601#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 /* Some code in Modules/signalmodule.c depends on sigaction() being
2603 * used here if HAVE_SIGACTION is defined. Fix that if this code
2604 * changes to invalidate that assumption.
2605 */
2606 struct sigaction context, ocontext;
2607 context.sa_handler = handler;
2608 sigemptyset(&context.sa_mask);
2609 context.sa_flags = 0;
2610 if (sigaction(sig, &context, &ocontext) == -1)
2611 return SIG_ERR;
2612 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002613#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 PyOS_sighandler_t oldhandler;
2615 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002616#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002618#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002620#endif
2621}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002622
2623/* Deprecated C API functions still provided for binary compatiblity */
2624
2625#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002626PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002627PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002630}
2631
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002632#undef PyParser_SimpleParseString
2633PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002634PyParser_SimpleParseString(const char *str, int start)
2635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002637}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002638
2639#undef PyRun_AnyFile
2640PyAPI_FUNC(int)
2641PyRun_AnyFile(FILE *fp, const char *name)
2642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002644}
2645
2646#undef PyRun_AnyFileEx
2647PyAPI_FUNC(int)
2648PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002651}
2652
2653#undef PyRun_AnyFileFlags
2654PyAPI_FUNC(int)
2655PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002658}
2659
2660#undef PyRun_File
2661PyAPI_FUNC(PyObject *)
2662PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002665}
2666
2667#undef PyRun_FileEx
2668PyAPI_FUNC(PyObject *)
2669PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002672}
2673
2674#undef PyRun_FileFlags
2675PyAPI_FUNC(PyObject *)
2676PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002680}
2681
2682#undef PyRun_SimpleFile
2683PyAPI_FUNC(int)
2684PyRun_SimpleFile(FILE *f, const char *p)
2685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002687}
2688
2689#undef PyRun_SimpleFileEx
2690PyAPI_FUNC(int)
2691PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002694}
2695
2696
2697#undef PyRun_String
2698PyAPI_FUNC(PyObject *)
2699PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002701 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002702}
2703
2704#undef PyRun_SimpleString
2705PyAPI_FUNC(int)
2706PyRun_SimpleString(const char *s)
2707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002709}
2710
2711#undef Py_CompileString
2712PyAPI_FUNC(PyObject *)
2713Py_CompileString(const char *str, const char *p, int s)
2714{
Georg Brandl8334fd92010-12-04 10:26:46 +00002715 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2716}
2717
2718#undef Py_CompileStringFlags
2719PyAPI_FUNC(PyObject *)
2720Py_CompileStringFlags(const char *str, const char *p, int s,
2721 PyCompilerFlags *flags)
2722{
2723 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002724}
2725
2726#undef PyRun_InteractiveOne
2727PyAPI_FUNC(int)
2728PyRun_InteractiveOne(FILE *f, const char *p)
2729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002731}
2732
2733#undef PyRun_InteractiveLoop
2734PyAPI_FUNC(int)
2735PyRun_InteractiveLoop(FILE *f, const char *p)
2736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002738}
2739
2740#ifdef __cplusplus
2741}
2742#endif