blob: dd3201757410c92d599d9e5676e04668815e41fc [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 Heimes33fe8092008-04-13 13:53:33 +000099/* PyModule_GetWarningsModule is no longer necessary as of 2.6
100since _warnings is builtin. This API should not be used. */
101PyObject *
102PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000105}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000106
Guido van Rossum25ce5661997-08-02 03:10:38 +0000107static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000108
Thomas Wouters7e474022000-07-16 12:04:32 +0000109/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000110
111int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000112Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000115}
116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117/* Global initializations. Can be undone by Py_Finalize(). Don't
118 call this twice without an intervening Py_Finalize() call. When
119 initializations fail, a fatal error is issued and the function does
120 not return. On return, the first thread and interpreter state have
121 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123 Locking: you must hold the interpreter lock while calling this.
124 (If the lock has not yet been initialized, that's equivalent to
125 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000126
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000128
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000129static int
130add_flag(int flag, const char *envs)
131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int env = atoi(envs);
133 if (flag < env)
134 flag = env;
135 if (flag < 1)
136 flag = 1;
137 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000138}
139
Christian Heimes5833a2f2008-10-30 21:40:04 +0000140static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000141get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000142{
Victor Stinner94908bb2010-08-18 21:23:25 +0000143 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000144 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200145 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000146
Victor Stinner94908bb2010-08-18 21:23:25 +0000147 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (!codec)
149 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000150
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200151 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 Py_CLEAR(codec);
153 if (!name)
154 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000155
Victor Stinner94908bb2010-08-18 21:23:25 +0000156 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100157 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000158 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000159 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000161 if (name_str == NULL) {
162 PyErr_NoMemory();
163 return NULL;
164 }
165 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000166
167error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000169 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000171}
Victor Stinner94908bb2010-08-18 21:23:25 +0000172
Victor Stinner94908bb2010-08-18 21:23:25 +0000173static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200174get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000175{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200176#ifdef MS_WINDOWS
177 char codepage[100];
178 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
179 return get_codec_name(codepage);
180#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000181 char* codeset = nl_langinfo(CODESET);
182 if (!codeset || codeset[0] == '\0') {
183 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
184 return NULL;
185 }
186 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200187#else
188 PyErr_SetNone(PyExc_NotImplementedError);
189 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000190#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200191}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000192
Brett Cannonfd074152012-04-14 14:10:13 -0400193static void
194import_init(PyInterpreterState *interp, PyObject *sysmod)
195{
196 PyObject *importlib;
197 PyObject *impmod;
198 PyObject *sys_modules;
199 PyObject *value;
200
201 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400202 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
203 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
204 }
205 else if (Py_VerboseFlag) {
206 PySys_FormatStderr("import _frozen_importlib # frozen\n");
207 }
208 importlib = PyImport_AddModule("_frozen_importlib");
209 if (importlib == NULL) {
210 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
211 "sys.modules");
212 }
213 interp->importlib = importlib;
214 Py_INCREF(interp->importlib);
215
216 /* Install _importlib as __import__ */
217 impmod = PyInit_imp();
218 if (impmod == NULL) {
219 Py_FatalError("Py_Initialize: can't import imp");
220 }
221 else if (Py_VerboseFlag) {
222 PySys_FormatStderr("import imp # builtin\n");
223 }
224 sys_modules = PyImport_GetModuleDict();
225 if (Py_VerboseFlag) {
226 PySys_FormatStderr("import sys # builtin\n");
227 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400228 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
229 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400230 }
231
Brett Cannone0d88a12012-04-25 20:54:04 -0400232 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400233 if (value == NULL) {
234 PyErr_Print();
235 Py_FatalError("Py_Initialize: importlib install failed");
236 }
237 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400238 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400239
240 _PyImportZip_Init();
241}
242
243
Guido van Rossuma027efa1997-05-05 20:56:21 +0000244void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200245_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyInterpreterState *interp;
248 PyThreadState *tstate;
249 PyObject *bimod, *sysmod, *pstderr;
250 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (initialized)
254 return;
255 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200256 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000257
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000258#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 /* Set up the LC_CTYPE locale, so we can obtain
260 the locale's charset without having to switch
261 locales. */
262 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000263#endif
264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
266 Py_DebugFlag = add_flag(Py_DebugFlag, p);
267 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
268 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
269 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
270 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
271 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
272 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100273 /* The variable is only tested for existence here; _PyRandom_Init will
274 check its value further. */
275 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
276 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
277
278 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 interp = PyInterpreterState_New();
281 if (interp == NULL)
282 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 tstate = PyThreadState_New(interp);
285 if (tstate == NULL)
286 Py_FatalError("Py_Initialize: can't make first thread");
287 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000288
Victor Stinner6961bd62010-08-17 22:26:51 +0000289#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000290 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
291 destroying the GIL might fail when it is being referenced from
292 another running thread (see issue #9901).
293 Instead we destroy the previously created GIL here, which ensures
294 that we can call Py_Initialize / Py_Finalize multiple times. */
295 _PyEval_FiniThreads();
296
297 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000298 _PyGILState_Init(interp, tstate);
299#endif /* WITH_THREAD */
300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (!_PyFrame_Init())
304 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (!_PyLong_Init())
307 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (!PyByteArray_Init())
310 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 interp->modules = PyDict_New();
315 if (interp->modules == NULL)
316 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200319 if (_PyUnicode_Init() < 0)
320 Py_FatalError("Py_Initialize: can't initialize unicode");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 bimod = _PyBuiltin_Init();
323 if (bimod == NULL)
324 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000325 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 interp->builtins = PyModule_GetDict(bimod);
327 if (interp->builtins == NULL)
328 Py_FatalError("Py_Initialize: can't initialize builtins dict");
329 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400332 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 sysmod = _PySys_Init();
335 if (sysmod == NULL)
336 Py_FatalError("Py_Initialize: can't initialize sys");
337 interp->sysdict = PyModule_GetDict(sysmod);
338 if (interp->sysdict == NULL)
339 Py_FatalError("Py_Initialize: can't initialize sys dict");
340 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000341 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 PySys_SetPath(Py_GetPath());
343 PyDict_SetItemString(interp->sysdict, "modules",
344 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 /* Set up a preliminary stderr printer until we have enough
347 infrastructure for the io module in place. */
348 pstderr = PyFile_NewStdPrinter(fileno(stderr));
349 if (pstderr == NULL)
350 Py_FatalError("Py_Initialize: can't set preliminary stderr");
351 PySys_SetObject("stderr", pstderr);
352 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000353 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000358
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000359 /* Initialize _warnings. */
360 _PyWarnings_Init();
361
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200362 if (!install_importlib)
363 return;
364
Brett Cannonfd074152012-04-14 14:10:13 -0400365 import_init(interp, sysmod);
366
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200367 /* initialize the faulthandler module */
368 if (_PyFaulthandler_Init())
369 Py_FatalError("Py_Initialize: can't initialize faulthandler");
370
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000371 _PyTime_Init();
372
Victor Stinner793b5312011-04-27 00:24:21 +0200373 if (initfsencoding(interp) < 0)
374 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 if (install_sigs)
377 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000378
Nick Coghlan85e729e2012-07-15 18:09:52 +1000379 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 if (initstdio() < 0)
381 Py_FatalError(
382 "Py_Initialize: can't initialize sys standard streams");
383
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000384 /* Initialize warnings. */
385 if (PySys_HasWarnOptions()) {
386 PyObject *warnings_module = PyImport_ImportModule("warnings");
387 if (warnings_module == NULL) {
388 fprintf(stderr, "'import warnings' failed; traceback:\n");
389 PyErr_Print();
390 }
391 Py_XDECREF(warnings_module);
392 }
393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (!Py_NoSiteFlag)
395 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000396}
397
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000398void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200399Py_InitializeEx(int install_sigs)
400{
401 _Py_InitializeEx_Private(install_sigs, 1);
402}
403
404void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000405Py_Initialize(void)
406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000408}
409
410
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000411#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000412extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000413#endif
414
Guido van Rossume8432ac2007-07-09 15:04:50 +0000415/* Flush stdout and stderr */
416
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100417static int
418file_is_closed(PyObject *fobj)
419{
420 int r;
421 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
422 if (tmp == NULL) {
423 PyErr_Clear();
424 return 0;
425 }
426 r = PyObject_IsTrue(tmp);
427 Py_DECREF(tmp);
428 if (r < 0)
429 PyErr_Clear();
430 return r > 0;
431}
432
Neal Norwitz2bad9702007-08-27 06:19:22 +0000433static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000434flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 PyObject *fout = PySys_GetObject("stdout");
437 PyObject *ferr = PySys_GetObject("stderr");
438 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200439 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000440
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100441 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200442 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000444 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 else
446 Py_DECREF(tmp);
447 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000448
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100449 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200450 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (tmp == NULL)
452 PyErr_Clear();
453 else
454 Py_DECREF(tmp);
455 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000456}
457
Guido van Rossum25ce5661997-08-02 03:10:38 +0000458/* Undo the effect of Py_Initialize().
459
460 Beware: if multiple interpreter and/or thread states exist, these
461 are not wiped out; only the current thread and interpreter state
462 are deleted. But since everything else is deleted, those other
463 interpreter and thread states should no longer be used.
464
465 (XXX We should do better, e.g. wipe out all interpreters and
466 threads.)
467
468 Locking: as above.
469
470*/
471
472void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000473Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 PyInterpreterState *interp;
476 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (!initialized)
479 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 /* The interpreter is still entirely intact at this point, and the
484 * exit funcs may be relying on that. In particular, if some thread
485 * or exit func is still waiting to do an import, the import machinery
486 * expects Py_IsInitialized() to return true. So don't say the
487 * interpreter is uninitialized until after the exit funcs have run.
488 * Note that Threading.py uses an exit func to do a join on all the
489 * threads created thru it, so this also protects pending imports in
490 * the threads created via Threading.
491 */
492 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* Get current thread state and interpreter pointer */
495 tstate = PyThreadState_GET();
496 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000497
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200498 /* Remaining threads (e.g. daemon threads) will automatically exit
499 after taking the GIL (in PyEval_RestoreThread()). */
500 _Py_Finalizing = tstate;
501 initialized = 0;
502
503 /* Flush stdout+stderr */
504 flush_std_files();
505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 /* Disable signal handling */
507 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 /* Clear type lookup cache */
510 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 /* Collect garbage. This may call finalizers; it's nice to call these
513 * before all modules are destroyed.
514 * XXX If a __del__ or weakref callback is triggered here, and tries to
515 * XXX import a module, bad things can happen, because Python no
516 * XXX longer believes it's initialized.
517 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
518 * XXX is easy to provoke that way. I've also seen, e.g.,
519 * XXX Exception exceptions.ImportError: 'No module named sha'
520 * XXX in <function callback at 0x008F5718> ignored
521 * XXX but I'm unclear on exactly how that one happens. In any case,
522 * XXX I haven't seen a real-life report of either of these.
523 */
524 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000525#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* With COUNT_ALLOCS, it helps to run GC multiple times:
527 each collection might release some types from the type
528 list, so they become garbage. */
529 while (PyGC_Collect() > 0)
530 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000531#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000532 /* We run this while most interpreter state is still alive, so that
533 debug information can be printed out */
534 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* Destroy all modules */
537 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 /* Flush stdout+stderr (again, in case more was printed) */
540 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100543 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 * XXX This is disabled because it caused too many problems. If
545 * XXX a __del__ or weakref callback triggers here, Python code has
546 * XXX a hard time running, because even the sys module has been
547 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
548 * XXX One symptom is a sequence of information-free messages
549 * XXX coming from threads (if a __del__ or callback is invoked,
550 * XXX other threads can execute too, and any exception they encounter
551 * XXX triggers a comedy of errors as subsystem after subsystem
552 * XXX fails to find what it *expects* to find in sys to help report
553 * XXX the exception and consequent unexpected failures). I've also
554 * XXX seen segfaults then, after adding print statements to the
555 * XXX Python code getting called.
556 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000557#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000559#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
562 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000563
Victor Stinner024e37a2011-03-31 01:31:06 +0200564 /* unload faulthandler module */
565 _PyFaulthandler_Fini();
566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000568#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000570#endif
571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000573
Tim Peters9cf25ce2003-04-17 15:21:01 +0000574#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 /* Display all objects still alive -- this can invoke arbitrary
576 * __repr__ overrides, so requires a mostly-intact interpreter.
577 * Alas, a lot of stuff may still be alive now that will be cleaned
578 * up later.
579 */
580 if (Py_GETENV("PYTHONDUMPREFS"))
581 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000582#endif /* Py_TRACE_REFS */
583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 /* Clear interpreter state */
585 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 /* Now we decref the exception classes. After this point nothing
588 can raise an exception. That's okay, because each Fini() method
589 below has been checked to make sure no exceptions are ever
590 raised.
591 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000596#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000598#endif /* WITH_THREAD */
599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 /* Delete current thread */
601 PyThreadState_Swap(NULL);
602 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000603
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 Pitrouf95a1b32010-05-09 15:52:27 +0000621 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000622 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 free((char*)Py_FileSystemDefaultEncoding);
624 Py_FileSystemDefaultEncoding = NULL;
625 }
Christian Heimesc8967002007-11-30 10:18:26 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 /* XXX Still allocated:
628 - various static ad-hoc pointers to interned strings
629 - int and float free list blocks
630 - whatever various modules and libraries allocate
631 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000634
Tim Peters269b2a62003-04-17 19:52:29 +0000635#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 /* Display addresses (& refcnts) of all objects still alive.
637 * An address can be used to find the repr of the object, printed
638 * above by _Py_PrintReferences.
639 */
640 if (Py_GETENV("PYTHONDUMPREFS"))
641 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000642#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000643#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400645 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000646#endif
647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649}
650
651/* Create and initialize a new interpreter and thread, and return the
652 new thread. This requires that Py_Initialize() has been called
653 first.
654
655 Unsuccessful initialization yields a NULL pointer. Note that *no*
656 exception information is available even in this case -- the
657 exception information is held in the thread, and there is no
658 thread.
659
660 Locking: as above.
661
662*/
663
664PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000665Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyInterpreterState *interp;
668 PyThreadState *tstate, *save_tstate;
669 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (!initialized)
672 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 interp = PyInterpreterState_New();
675 if (interp == NULL)
676 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 tstate = PyThreadState_New(interp);
679 if (tstate == NULL) {
680 PyInterpreterState_Delete(interp);
681 return NULL;
682 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000689
Victor Stinner49d3f252010-10-17 01:24:53 +0000690 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 if (bimod != NULL) {
692 interp->builtins = PyModule_GetDict(bimod);
693 if (interp->builtins == NULL)
694 goto handle_error;
695 Py_INCREF(interp->builtins);
696 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400699 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000700
Victor Stinner49d3f252010-10-17 01:24:53 +0000701 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (bimod != NULL && sysmod != NULL) {
703 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 interp->sysdict = PyModule_GetDict(sysmod);
706 if (interp->sysdict == NULL)
707 goto handle_error;
708 Py_INCREF(interp->sysdict);
709 PySys_SetPath(Py_GetPath());
710 PyDict_SetItemString(interp->sysdict, "modules",
711 interp->modules);
712 /* Set up a preliminary stderr printer until we have enough
713 infrastructure for the io module in place. */
714 pstderr = PyFile_NewStdPrinter(fileno(stderr));
715 if (pstderr == NULL)
716 Py_FatalError("Py_Initialize: can't set preliminary stderr");
717 PySys_SetObject("stderr", pstderr);
718 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000719 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200722
Brett Cannonfd074152012-04-14 14:10:13 -0400723 import_init(interp, sysmod);
724
Victor Stinner793b5312011-04-27 00:24:21 +0200725 if (initfsencoding(interp) < 0)
726 goto handle_error;
727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 if (initstdio() < 0)
729 Py_FatalError(
730 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000731 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (!Py_NoSiteFlag)
733 initsite();
734 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 if (!PyErr_Occurred())
737 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000738
Thomas Wouters89f507f2006-12-13 04:49:30 +0000739handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000741
Victor Stinnerc40a3502011-04-27 00:20:27 +0200742 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyThreadState_Clear(tstate);
744 PyThreadState_Swap(save_tstate);
745 PyThreadState_Delete(tstate);
746 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000749}
750
751/* Delete an interpreter and its last thread. This requires that the
752 given thread state is current, that the thread has no remaining
753 frames, and that it is its interpreter's only remaining thread.
754 It is a fatal error to violate these constraints.
755
756 (Py_Finalize() doesn't have these constraints -- it zaps
757 everything, regardless.)
758
759 Locking: as above.
760
761*/
762
763void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000764Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (tstate != PyThreadState_GET())
769 Py_FatalError("Py_EndInterpreter: thread is not current");
770 if (tstate->frame != NULL)
771 Py_FatalError("Py_EndInterpreter: thread still has a frame");
772 if (tstate != interp->tstate_head || tstate->next != NULL)
773 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 PyImport_Cleanup();
776 PyInterpreterState_Clear(interp);
777 PyThreadState_Swap(NULL);
778 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000779}
780
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200781#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000782static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200783#else
784static wchar_t *progname = L"python3";
785#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000786
787void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000788Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (pn && *pn)
791 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000792}
793
Martin v. Löwis790465f2008-04-05 20:41:37 +0000794wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000795Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000798}
799
Martin v. Löwis790465f2008-04-05 20:41:37 +0000800static wchar_t *default_home = NULL;
801static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000802
803void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000804Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000807}
808
Martin v. Löwis790465f2008-04-05 20:41:37 +0000809wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000810Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 wchar_t *home = default_home;
813 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
814 char* chome = Py_GETENV("PYTHONHOME");
815 if (chome) {
816 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
817 if (r != (size_t)-1 && r <= PATH_MAX)
818 home = env_home;
819 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 }
822 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000823}
824
Guido van Rossum6135a871995-01-09 17:53:26 +0000825/* Create __main__ module */
826
827static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000828initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyObject *m, *d;
831 m = PyImport_AddModule("__main__");
832 if (m == NULL)
833 Py_FatalError("can't create __main__ module");
834 d = PyModule_GetDict(m);
835 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
836 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000837 if (bimod == NULL) {
838 Py_FatalError("Failed to retrieve builtins module");
839 }
840 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
841 Py_FatalError("Failed to initialize __main__.__builtins__");
842 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 Py_DECREF(bimod);
844 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000845 /* Main is a little special - imp.is_builtin("__main__") will return
846 * False, but BuiltinImporter is still the most appropriate initial
847 * setting for its __loader__ attribute. A more suitable value will
848 * be set if __main__ gets further initialized later in the startup
849 * process.
850 */
851 if (PyDict_GetItemString(d, "__loader__") == NULL) {
852 PyObject *loader = PyObject_GetAttrString(interp->importlib,
853 "BuiltinImporter");
854 if (loader == NULL) {
855 Py_FatalError("Failed to retrieve BuiltinImporter");
856 }
857 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
858 Py_FatalError("Failed to initialize __main__.__loader__");
859 }
860 Py_DECREF(loader);
861 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000862}
863
Victor Stinner793b5312011-04-27 00:24:21 +0200864static int
865initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000866{
867 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000868
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200869 if (Py_FileSystemDefaultEncoding == NULL)
870 {
871 Py_FileSystemDefaultEncoding = get_locale_encoding();
872 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000873 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000874
Victor Stinnere4743092010-10-19 00:05:51 +0000875 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200876 interp->fscodec_initialized = 1;
877 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000878 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000879
880 /* the encoding is mbcs, utf-8 or ascii */
881 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
882 if (!codec) {
883 /* Such error can only occurs in critical situations: no more
884 * memory, import a module of the standard library failed,
885 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200886 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000887 }
Victor Stinner793b5312011-04-27 00:24:21 +0200888 Py_DECREF(codec);
889 interp->fscodec_initialized = 1;
890 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000891}
892
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000893/* Import the site module (not into __main__ though) */
894
895static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000896initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 PyObject *m;
899 m = PyImport_ImportModule("site");
900 if (m == NULL) {
901 PyErr_Print();
902 Py_Finalize();
903 exit(1);
904 }
905 else {
906 Py_DECREF(m);
907 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000908}
909
Antoine Pitrou05608432009-01-09 18:53:14 +0000910static PyObject*
911create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 int fd, int write_mode, char* name,
913 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
916 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000917 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyObject *line_buffering;
919 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200920 _Py_IDENTIFIER(open);
921 _Py_IDENTIFIER(isatty);
922 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200923 _Py_IDENTIFIER(name);
924 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 /* stdin is always opened in buffered mode, first because it shouldn't
927 make a difference in common use cases, second because TextIOWrapper
928 depends on the presence of a read1() method which only exists on
929 buffered streams.
930 */
931 if (Py_UnbufferedStdioFlag && write_mode)
932 buffering = 0;
933 else
934 buffering = -1;
935 if (write_mode)
936 mode = "wb";
937 else
938 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200939 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
940 fd, mode, buffering,
941 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if (buf == NULL)
943 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200946 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200947 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 if (raw == NULL)
949 goto error;
950 }
951 else {
952 raw = buf;
953 Py_INCREF(raw);
954 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200957 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200959 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 if (res == NULL)
961 goto error;
962 isatty = PyObject_IsTrue(res);
963 Py_DECREF(res);
964 if (isatty == -1)
965 goto error;
966 if (isatty || Py_UnbufferedStdioFlag)
967 line_buffering = Py_True;
968 else
969 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 Py_CLEAR(raw);
972 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000973
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000974#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +0200975 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
976 newlines to "\n".
977 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
978 newline = NULL;
979#else
980 /* sys.stdin: split lines at "\n".
981 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
982 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000983#endif
984
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200985 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
986 buf, encoding, errors,
987 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 Py_CLEAR(buf);
989 if (stream == NULL)
990 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (write_mode)
993 mode = "w";
994 else
995 mode = "r";
996 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200997 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 goto error;
999 Py_CLEAR(text);
1000 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001001
1002error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 Py_XDECREF(buf);
1004 Py_XDECREF(stream);
1005 Py_XDECREF(text);
1006 Py_XDECREF(raw);
1007 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001008}
1009
Antoine Pitrou11942a52011-11-28 19:08:36 +01001010static int
1011is_valid_fd(int fd)
1012{
1013 int dummy_fd;
1014 if (fd < 0 || !_PyVerify_fd(fd))
1015 return 0;
1016 dummy_fd = dup(fd);
1017 if (dummy_fd < 0)
1018 return 0;
1019 close(dummy_fd);
1020 return 1;
1021}
1022
Georg Brandl1a3284e2007-12-02 09:40:06 +00001023/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001024static int
1025initstdio(void)
1026{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 PyObject *iomod = NULL, *wrapper;
1028 PyObject *bimod = NULL;
1029 PyObject *m;
1030 PyObject *std = NULL;
1031 int status = 0, fd;
1032 PyObject * encoding_attr;
1033 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* Hack to avoid a nasty recursion issue when Python is invoked
1036 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1037 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1038 goto error;
1039 }
1040 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1043 goto error;
1044 }
1045 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 if (!(bimod = PyImport_ImportModule("builtins"))) {
1048 goto error;
1049 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 if (!(iomod = PyImport_ImportModule("io"))) {
1052 goto error;
1053 }
1054 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1055 goto error;
1056 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 /* Set builtins.open */
1059 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001060 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 goto error;
1062 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001063 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 encoding = Py_GETENV("PYTHONIOENCODING");
1066 errors = NULL;
1067 if (encoding) {
1068 encoding = strdup(encoding);
1069 errors = strchr(encoding, ':');
1070 if (errors) {
1071 *errors = '\0';
1072 errors++;
1073 }
1074 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 /* Set sys.stdin */
1077 fd = fileno(stdin);
1078 /* Under some conditions stdin, stdout and stderr may not be connected
1079 * and fileno() may point to an invalid file descriptor. For example
1080 * GUI apps don't have valid standard streams by default.
1081 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001082 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 std = Py_None;
1084 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 }
1086 else {
1087 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1088 if (std == NULL)
1089 goto error;
1090 } /* if (fd < 0) */
1091 PySys_SetObject("__stdin__", std);
1092 PySys_SetObject("stdin", std);
1093 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 /* Set sys.stdout */
1096 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001097 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 std = Py_None;
1099 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 }
1101 else {
1102 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1103 if (std == NULL)
1104 goto error;
1105 } /* if (fd < 0) */
1106 PySys_SetObject("__stdout__", std);
1107 PySys_SetObject("stdout", std);
1108 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001109
Guido van Rossum98297ee2007-11-06 21:34:58 +00001110#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 /* Set sys.stderr, replaces the preliminary stderr */
1112 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001113 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 std = Py_None;
1115 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 }
1117 else {
1118 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1119 if (std == NULL)
1120 goto error;
1121 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 /* Same as hack above, pre-import stderr's codec to avoid recursion
1124 when import.c tries to write to stderr in verbose mode. */
1125 encoding_attr = PyObject_GetAttrString(std, "encoding");
1126 if (encoding_attr != NULL) {
1127 const char * encoding;
1128 encoding = _PyUnicode_AsString(encoding_attr);
1129 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001130 PyObject *codec_info = _PyCodec_Lookup(encoding);
1131 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001133 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 }
1135 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 PySys_SetObject("__stderr__", std);
1138 PySys_SetObject("stderr", std);
1139 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001140#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001143 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 status = -1;
1145 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (encoding)
1148 free(encoding);
1149 Py_XDECREF(bimod);
1150 Py_XDECREF(iomod);
1151 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001152}
1153
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001154/* Parse input from a file and execute it */
1155
1156int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001157PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 if (filename == NULL)
1161 filename = "???";
1162 if (Py_FdIsInteractive(fp, filename)) {
1163 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1164 if (closeit)
1165 fclose(fp);
1166 return err;
1167 }
1168 else
1169 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001170}
1171
1172int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001173PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 PyObject *v;
1176 int ret;
1177 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 if (flags == NULL) {
1180 flags = &local_flags;
1181 local_flags.cf_flags = 0;
1182 }
1183 v = PySys_GetObject("ps1");
1184 if (v == NULL) {
1185 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1186 Py_XDECREF(v);
1187 }
1188 v = PySys_GetObject("ps2");
1189 if (v == NULL) {
1190 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1191 Py_XDECREF(v);
1192 }
1193 for (;;) {
1194 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1195 PRINT_TOTAL_REFS();
1196 if (ret == E_EOF)
1197 return 0;
1198 /*
1199 if (ret == E_NOMEM)
1200 return -1;
1201 */
1202 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001203}
1204
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001205/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001206static int PARSER_FLAGS(PyCompilerFlags *flags)
1207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 int parser_flags = 0;
1209 if (!flags)
1210 return 0;
1211 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1212 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1213 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1214 parser_flags |= PyPARSE_IGNORE_COOKIE;
1215 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1216 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1217 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001218}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001219
Thomas Wouters89f507f2006-12-13 04:49:30 +00001220#if 0
1221/* Keep an example of flags with future keyword support. */
1222#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1224 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1225 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1226 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001227#endif
1228
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001229int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001230PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 PyObject *m, *d, *v, *w, *oenc = NULL;
1233 mod_ty mod;
1234 PyArena *arena;
1235 char *ps1 = "", *ps2 = "", *enc = NULL;
1236 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001237 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 if (fp == stdin) {
1240 /* Fetch encoding from sys.stdin */
1241 v = PySys_GetObject("stdin");
1242 if (v == NULL || v == Py_None)
1243 return -1;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001244 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 if (!oenc)
1246 return -1;
1247 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001248 if (enc == NULL)
1249 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 }
1251 v = PySys_GetObject("ps1");
1252 if (v != NULL) {
1253 v = PyObject_Str(v);
1254 if (v == NULL)
1255 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001256 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001258 if (ps1 == NULL) {
1259 PyErr_Clear();
1260 ps1 = "";
1261 }
1262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 }
1264 w = PySys_GetObject("ps2");
1265 if (w != NULL) {
1266 w = PyObject_Str(w);
1267 if (w == NULL)
1268 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001269 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001271 if (ps2 == NULL) {
1272 PyErr_Clear();
1273 ps2 = "";
1274 }
1275 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 }
1277 arena = PyArena_New();
1278 if (arena == NULL) {
1279 Py_XDECREF(v);
1280 Py_XDECREF(w);
1281 Py_XDECREF(oenc);
1282 return -1;
1283 }
1284 mod = PyParser_ASTFromFile(fp, filename, enc,
1285 Py_single_input, ps1, ps2,
1286 flags, &errcode, arena);
1287 Py_XDECREF(v);
1288 Py_XDECREF(w);
1289 Py_XDECREF(oenc);
1290 if (mod == NULL) {
1291 PyArena_Free(arena);
1292 if (errcode == E_EOF) {
1293 PyErr_Clear();
1294 return E_EOF;
1295 }
1296 PyErr_Print();
1297 return -1;
1298 }
1299 m = PyImport_AddModule("__main__");
1300 if (m == NULL) {
1301 PyArena_Free(arena);
1302 return -1;
1303 }
1304 d = PyModule_GetDict(m);
1305 v = run_mod(mod, filename, d, d, flags, arena);
1306 PyArena_Free(arena);
1307 flush_io();
1308 if (v == NULL) {
1309 PyErr_Print();
1310 return -1;
1311 }
1312 Py_DECREF(v);
1313 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001314}
1315
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001316/* Check whether a file maybe a pyc file: Look at the extension,
1317 the file type, and, if we may close it, at the first few bytes. */
1318
1319static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001320maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1323 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* Only look into the file if we are allowed to close it, since
1326 it then should also be seekable. */
1327 if (closeit) {
1328 /* Read only two bytes of the magic. If the file was opened in
1329 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1330 be read as they are on disk. */
1331 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1332 unsigned char buf[2];
1333 /* Mess: In case of -x, the stream is NOT at its start now,
1334 and ungetc() was used to push back the first newline,
1335 which makes the current stream position formally undefined,
1336 and a x-platform nightmare.
1337 Unfortunately, we have no direct way to know whether -x
1338 was specified. So we use a terrible hack: if the current
1339 stream position is not 0, we assume -x was specified, and
1340 give up. Bug 132850 on SourceForge spells out the
1341 hopelessness of trying anything else (fseek and ftell
1342 don't work predictably x-platform for text-mode files).
1343 */
1344 int ispyc = 0;
1345 if (ftell(fp) == 0) {
1346 if (fread(buf, 1, 2, fp) == 2 &&
1347 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1348 ispyc = 1;
1349 rewind(fp);
1350 }
1351 return ispyc;
1352 }
1353 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001354}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001355
Guido van Rossum0df002c2000-08-27 19:21:52 +00001356int
Nick Coghlanceda83c2012-07-15 23:18:08 +10001357static set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001358{
1359 PyInterpreterState *interp;
1360 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001361 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001362 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001363
1364 filename_obj = PyUnicode_DecodeFSDefault(filename);
1365 if (filename_obj == NULL)
1366 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001367 /* Get current thread state and interpreter pointer */
1368 tstate = PyThreadState_GET();
1369 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001370 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1371 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001372 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001373 return -1;
1374 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001375 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001376 Py_DECREF(loader_type);
1377 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001378 return -1;
1379 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001380 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1381 result = -1;
1382 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001383 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001384 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001385}
1386
1387int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001388PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 PyObject *m, *d, *v;
1392 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001393 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001394 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 m = PyImport_AddModule("__main__");
1397 if (m == NULL)
1398 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001399 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 d = PyModule_GetDict(m);
1401 if (PyDict_GetItemString(d, "__file__") == NULL) {
1402 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001403 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001405 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1407 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001408 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001410 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1411 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001412 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001413 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 set_file_name = 1;
1415 Py_DECREF(f);
1416 }
1417 len = strlen(filename);
1418 ext = filename + len - (len > 4 ? 4 : 0);
1419 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001420 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 /* Try to run a pyc file. First, re-open in binary */
1422 if (closeit)
1423 fclose(fp);
Christian Heimes04ac4c12012-09-11 15:47:28 +02001424 if ((pyc_fp = fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 goto done;
1427 }
1428 /* Turn on optimization if a .pyo file is given */
1429 if (strcmp(ext, ".pyo") == 0)
1430 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001431
1432 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1433 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1434 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001435 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001436 goto done;
1437 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001438 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1439 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001441 /* When running from stdin, leave __main__.__loader__ alone */
1442 if (strcmp(filename, "<stdin>") != 0 &&
1443 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1444 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1445 ret = -1;
1446 goto done;
1447 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1449 closeit, flags);
1450 }
1451 flush_io();
1452 if (v == NULL) {
1453 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 goto done;
1455 }
1456 Py_DECREF(v);
1457 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001458 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1460 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001461 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001463}
1464
1465int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001466PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 PyObject *m, *d, *v;
1469 m = PyImport_AddModule("__main__");
1470 if (m == NULL)
1471 return -1;
1472 d = PyModule_GetDict(m);
1473 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1474 if (v == NULL) {
1475 PyErr_Print();
1476 return -1;
1477 }
1478 Py_DECREF(v);
1479 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001480}
1481
Barry Warsaw035574d1997-08-29 22:07:17 +00001482static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001483parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 long hold;
1487 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001488 _Py_IDENTIFIER(msg);
1489 _Py_IDENTIFIER(filename);
1490 _Py_IDENTIFIER(lineno);
1491 _Py_IDENTIFIER(offset);
1492 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001493
Benjamin Peterson80d50422012-04-03 00:30:38 -04001494 *message = NULL;
1495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001497 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001498 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001500
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001501 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001502 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001504 if (v == Py_None) {
1505 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001507 }
1508 else {
1509 *filename = _PyUnicode_AsString(v);
1510 Py_DECREF(v);
1511 if (!*filename)
1512 goto finally;
1513 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001514
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001515 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001516 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 goto finally;
1518 hold = PyLong_AsLong(v);
1519 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (hold < 0 && PyErr_Occurred())
1521 goto finally;
1522 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001523
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001524 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001525 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 goto finally;
1527 if (v == Py_None) {
1528 *offset = -1;
1529 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 } else {
1531 hold = PyLong_AsLong(v);
1532 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 if (hold < 0 && PyErr_Occurred())
1534 goto finally;
1535 *offset = (int)hold;
1536 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001537
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001538 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001539 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001541 if (v == Py_None) {
1542 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001544 }
1545 else {
1546 *text = _PyUnicode_AsString(v);
1547 Py_DECREF(v);
1548 if (!*text)
1549 goto finally;
1550 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001552
1553finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001554 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001556}
1557
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001558void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001559PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001562}
1563
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001564static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001565print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 char *nl;
1568 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001569 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1570 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 for (;;) {
1572 nl = strchr(text, '\n');
1573 if (nl == NULL || nl-text >= offset)
1574 break;
1575 offset -= (int)(nl+1-text);
1576 text = nl+1;
1577 }
1578 while (*text == ' ' || *text == '\t') {
1579 text++;
1580 offset--;
1581 }
1582 }
1583 PyFile_WriteString(" ", f);
1584 PyFile_WriteString(text, f);
1585 if (*text == '\0' || text[strlen(text)-1] != '\n')
1586 PyFile_WriteString("\n", f);
1587 if (offset == -1)
1588 return;
1589 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001590 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001593}
1594
Guido van Rossum66e8e862001-03-23 17:54:43 +00001595static void
1596handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 PyObject *exception, *value, *tb;
1599 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 if (Py_InspectFlag)
1602 /* Don't exit if -i flag was given. This flag is set to 0
1603 * when entering interactive mode for inspecting. */
1604 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 PyErr_Fetch(&exception, &value, &tb);
1607 fflush(stdout);
1608 if (value == NULL || value == Py_None)
1609 goto done;
1610 if (PyExceptionInstance_Check(value)) {
1611 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001612 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001613 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 if (code) {
1615 Py_DECREF(value);
1616 value = code;
1617 if (value == Py_None)
1618 goto done;
1619 }
1620 /* If we failed to dig out the 'code' attribute,
1621 just let the else clause below print the error. */
1622 }
1623 if (PyLong_Check(value))
1624 exitcode = (int)PyLong_AsLong(value);
1625 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001626 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001627 if (sys_stderr != NULL && sys_stderr != Py_None) {
1628 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1629 } else {
1630 PyObject_Print(value, stderr, Py_PRINT_RAW);
1631 fflush(stderr);
1632 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 PySys_WriteStderr("\n");
1634 exitcode = 1;
1635 }
Tim Peterscf615b52003-04-19 18:47:02 +00001636 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 /* Restore and clear the exception info, in order to properly decref
1638 * the exception, value, and traceback. If we just exit instead,
1639 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1640 * some finalizers from running.
1641 */
1642 PyErr_Restore(exception, value, tb);
1643 PyErr_Clear();
1644 Py_Exit(exitcode);
1645 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001646}
1647
1648void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001649PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1654 handle_system_exit();
1655 }
1656 PyErr_Fetch(&exception, &v, &tb);
1657 if (exception == NULL)
1658 return;
1659 PyErr_NormalizeException(&exception, &v, &tb);
1660 if (tb == NULL) {
1661 tb = Py_None;
1662 Py_INCREF(tb);
1663 }
1664 PyException_SetTraceback(v, tb);
1665 if (exception == NULL)
1666 return;
1667 /* Now we know v != NULL too */
1668 if (set_sys_last_vars) {
1669 PySys_SetObject("last_type", exception);
1670 PySys_SetObject("last_value", v);
1671 PySys_SetObject("last_traceback", tb);
1672 }
1673 hook = PySys_GetObject("excepthook");
1674 if (hook) {
1675 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1676 PyObject *result = PyEval_CallObject(hook, args);
1677 if (result == NULL) {
1678 PyObject *exception2, *v2, *tb2;
1679 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1680 handle_system_exit();
1681 }
1682 PyErr_Fetch(&exception2, &v2, &tb2);
1683 PyErr_NormalizeException(&exception2, &v2, &tb2);
1684 /* It should not be possible for exception2 or v2
1685 to be NULL. However PyErr_Display() can't
1686 tolerate NULLs, so just be safe. */
1687 if (exception2 == NULL) {
1688 exception2 = Py_None;
1689 Py_INCREF(exception2);
1690 }
1691 if (v2 == NULL) {
1692 v2 = Py_None;
1693 Py_INCREF(v2);
1694 }
1695 fflush(stdout);
1696 PySys_WriteStderr("Error in sys.excepthook:\n");
1697 PyErr_Display(exception2, v2, tb2);
1698 PySys_WriteStderr("\nOriginal exception was:\n");
1699 PyErr_Display(exception, v, tb);
1700 Py_DECREF(exception2);
1701 Py_DECREF(v2);
1702 Py_XDECREF(tb2);
1703 }
1704 Py_XDECREF(result);
1705 Py_XDECREF(args);
1706 } else {
1707 PySys_WriteStderr("sys.excepthook is missing\n");
1708 PyErr_Display(exception, v, tb);
1709 }
1710 Py_XDECREF(exception);
1711 Py_XDECREF(v);
1712 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001713}
1714
Benjamin Petersone6528212008-07-15 15:32:09 +00001715static void
1716print_exception(PyObject *f, PyObject *value)
1717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 int err = 0;
1719 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001720 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 if (!PyExceptionInstance_Check(value)) {
1723 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1724 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1725 PyFile_WriteString(" found\n", f);
1726 return;
1727 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 Py_INCREF(value);
1730 fflush(stdout);
1731 type = (PyObject *) Py_TYPE(value);
1732 tb = PyException_GetTraceback(value);
1733 if (tb && tb != Py_None)
1734 err = PyTraceBack_Print(tb, f);
1735 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001736 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 {
1738 PyObject *message;
1739 const char *filename, *text;
1740 int lineno, offset;
1741 if (!parse_syntax_error(value, &message, &filename,
1742 &lineno, &offset, &text))
1743 PyErr_Clear();
1744 else {
1745 char buf[10];
1746 PyFile_WriteString(" File \"", f);
1747 if (filename == NULL)
1748 PyFile_WriteString("<string>", f);
1749 else
1750 PyFile_WriteString(filename, f);
1751 PyFile_WriteString("\", line ", f);
1752 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1753 PyFile_WriteString(buf, f);
1754 PyFile_WriteString("\n", f);
1755 if (text != NULL)
1756 print_error_text(f, offset, text);
1757 Py_DECREF(value);
1758 value = message;
1759 /* Can't be bothered to check all those
1760 PyFile_WriteString() calls */
1761 if (PyErr_Occurred())
1762 err = -1;
1763 }
1764 }
1765 if (err) {
1766 /* Don't do anything else */
1767 }
1768 else {
1769 PyObject* moduleName;
1770 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001771 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 assert(PyExceptionClass_Check(type));
1773 className = PyExceptionClass_Name(type);
1774 if (className != NULL) {
1775 char *dot = strrchr(className, '.');
1776 if (dot != NULL)
1777 className = dot+1;
1778 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001779
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001780 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1782 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001783 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 err = PyFile_WriteString("<unknown>", f);
1785 }
1786 else {
1787 char* modstr = _PyUnicode_AsString(moduleName);
1788 if (modstr && strcmp(modstr, "builtins"))
1789 {
1790 err = PyFile_WriteString(modstr, f);
1791 err += PyFile_WriteString(".", f);
1792 }
1793 Py_DECREF(moduleName);
1794 }
1795 if (err == 0) {
1796 if (className == NULL)
1797 err = PyFile_WriteString("<unknown>", f);
1798 else
1799 err = PyFile_WriteString(className, f);
1800 }
1801 }
1802 if (err == 0 && (value != Py_None)) {
1803 PyObject *s = PyObject_Str(value);
1804 /* only print colon if the str() of the
1805 object is not the empty string
1806 */
1807 if (s == NULL)
1808 err = -1;
1809 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001810 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 err = PyFile_WriteString(": ", f);
1812 if (err == 0)
1813 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1814 Py_XDECREF(s);
1815 }
1816 /* try to write a newline in any case */
1817 err += PyFile_WriteString("\n", f);
1818 Py_XDECREF(tb);
1819 Py_DECREF(value);
1820 /* If an error happened here, don't show it.
1821 XXX This is wrong, but too many callers rely on this behavior. */
1822 if (err != 0)
1823 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001824}
1825
1826static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 "\nThe above exception was the direct cause "
1828 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001829
1830static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 "\nDuring handling of the above exception, "
1832 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001833
1834static void
1835print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 int err = 0, res;
1838 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 if (seen != NULL) {
1841 /* Exception chaining */
1842 if (PySet_Add(seen, value) == -1)
1843 PyErr_Clear();
1844 else if (PyExceptionInstance_Check(value)) {
1845 cause = PyException_GetCause(value);
1846 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001847 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 res = PySet_Contains(seen, cause);
1849 if (res == -1)
1850 PyErr_Clear();
1851 if (res == 0) {
1852 print_exception_recursive(
1853 f, cause, seen);
1854 err |= PyFile_WriteString(
1855 cause_message, f);
1856 }
1857 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001858 else if (context &&
1859 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001860 res = PySet_Contains(seen, context);
1861 if (res == -1)
1862 PyErr_Clear();
1863 if (res == 0) {
1864 print_exception_recursive(
1865 f, context, seen);
1866 err |= PyFile_WriteString(
1867 context_message, f);
1868 }
1869 }
1870 Py_XDECREF(context);
1871 Py_XDECREF(cause);
1872 }
1873 }
1874 print_exception(f, value);
1875 if (err != 0)
1876 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001877}
1878
Thomas Wouters477c8d52006-05-27 19:21:47 +00001879void
1880PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 PyObject *seen;
1883 PyObject *f = PySys_GetObject("stderr");
1884 if (f == Py_None) {
1885 /* pass */
1886 }
1887 else if (f == NULL) {
1888 _PyObject_Dump(value);
1889 fprintf(stderr, "lost sys.stderr\n");
1890 }
1891 else {
1892 /* We choose to ignore seen being possibly NULL, and report
1893 at least the main exception (it could be a MemoryError).
1894 */
1895 seen = PySet_New(NULL);
1896 if (seen == NULL)
1897 PyErr_Clear();
1898 print_exception_recursive(f, value, seen);
1899 Py_XDECREF(seen);
1900 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001901}
1902
Guido van Rossum82598051997-03-05 00:20:32 +00001903PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001904PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 PyObject *ret = NULL;
1908 mod_ty mod;
1909 PyArena *arena = PyArena_New();
1910 if (arena == NULL)
1911 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1914 if (mod != NULL)
1915 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1916 PyArena_Free(arena);
1917 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001918}
1919
1920PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001921PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 PyObject *ret;
1925 mod_ty mod;
1926 PyArena *arena = PyArena_New();
1927 if (arena == NULL)
1928 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1931 flags, NULL, arena);
1932 if (closeit)
1933 fclose(fp);
1934 if (mod == NULL) {
1935 PyArena_Free(arena);
1936 return NULL;
1937 }
1938 ret = run_mod(mod, filename, globals, locals, flags, arena);
1939 PyArena_Free(arena);
1940 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001941}
1942
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001943static void
1944flush_io(void)
1945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 PyObject *f, *r;
1947 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001948 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 /* Save the current exception */
1951 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 f = PySys_GetObject("stderr");
1954 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001955 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 if (r)
1957 Py_DECREF(r);
1958 else
1959 PyErr_Clear();
1960 }
1961 f = PySys_GetObject("stdout");
1962 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001963 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 if (r)
1965 Py_DECREF(r);
1966 else
1967 PyErr_Clear();
1968 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001971}
1972
Guido van Rossum82598051997-03-05 00:20:32 +00001973static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001974run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 PyCodeObject *co;
1978 PyObject *v;
1979 co = PyAST_Compile(mod, filename, flags, arena);
1980 if (co == NULL)
1981 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001982 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 Py_DECREF(co);
1984 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001985}
1986
Guido van Rossum82598051997-03-05 00:20:32 +00001987static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001988run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001990{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 PyCodeObject *co;
1992 PyObject *v;
1993 long magic;
1994 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 magic = PyMarshal_ReadLongFromFile(fp);
1997 if (magic != PyImport_GetMagicNumber()) {
1998 PyErr_SetString(PyExc_RuntimeError,
1999 "Bad magic number in .pyc file");
2000 return NULL;
2001 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002002 /* Skip mtime and size */
2003 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 (void) PyMarshal_ReadLongFromFile(fp);
2005 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 if (v == NULL || !PyCode_Check(v)) {
2007 Py_XDECREF(v);
2008 PyErr_SetString(PyExc_RuntimeError,
2009 "Bad code object in .pyc file");
2010 return NULL;
2011 }
2012 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002013 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 if (v && flags)
2015 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2016 Py_DECREF(co);
2017 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002018}
2019
Guido van Rossum82598051997-03-05 00:20:32 +00002020PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00002021Py_CompileStringExFlags(const char *str, const char *filename, int start,
2022 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 PyCodeObject *co;
2025 mod_ty mod;
2026 PyArena *arena = PyArena_New();
2027 if (arena == NULL)
2028 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
2031 if (mod == NULL) {
2032 PyArena_Free(arena);
2033 return NULL;
2034 }
2035 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2036 PyObject *result = PyAST_mod2obj(mod);
2037 PyArena_Free(arena);
2038 return result;
2039 }
Georg Brandl8334fd92010-12-04 10:26:46 +00002040 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 PyArena_Free(arena);
2042 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002043}
2044
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002045/* For use in Py_LIMITED_API */
2046#undef Py_CompileString
2047PyObject *
2048PyCompileString(const char *str, const char *filename, int start)
2049{
2050 return Py_CompileStringFlags(str, filename, start, NULL);
2051}
2052
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002053struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002054Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 struct symtable *st;
2057 mod_ty mod;
2058 PyCompilerFlags flags;
2059 PyArena *arena = PyArena_New();
2060 if (arena == NULL)
2061 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 flags.cf_flags = 0;
2064 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
2065 if (mod == NULL) {
2066 PyArena_Free(arena);
2067 return NULL;
2068 }
2069 st = PySymtable_Build(mod, filename, 0);
2070 PyArena_Free(arena);
2071 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002072}
2073
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002074/* Preferred access to parser is through AST. */
2075mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002076PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 mod_ty mod;
2080 PyCompilerFlags localflags;
2081 perrdetail err;
2082 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
2085 &_PyParser_Grammar, start, &err,
2086 &iflags);
2087 if (flags == NULL) {
2088 localflags.cf_flags = 0;
2089 flags = &localflags;
2090 }
2091 if (n) {
2092 flags->cf_flags |= iflags & PyCF_MASK;
2093 mod = PyAST_FromNode(n, flags, filename, arena);
2094 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 }
2096 else {
2097 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002098 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002100 err_free(&err);
2101 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002102}
2103
2104mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00002105PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 int start, char *ps1,
2107 char *ps2, PyCompilerFlags *flags, int *errcode,
2108 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 mod_ty mod;
2111 PyCompilerFlags localflags;
2112 perrdetail err;
2113 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
2116 &_PyParser_Grammar,
2117 start, ps1, ps2, &err, &iflags);
2118 if (flags == NULL) {
2119 localflags.cf_flags = 0;
2120 flags = &localflags;
2121 }
2122 if (n) {
2123 flags->cf_flags |= iflags & PyCF_MASK;
2124 mod = PyAST_FromNode(n, flags, filename, arena);
2125 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 }
2127 else {
2128 err_input(&err);
2129 if (errcode)
2130 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002131 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002133 err_free(&err);
2134 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002135}
2136
Guido van Rossuma110aa61994-08-29 12:50:44 +00002137/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002138
Guido van Rossuma110aa61994-08-29 12:50:44 +00002139node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002140PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 perrdetail err;
2143 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2144 &_PyParser_Grammar,
2145 start, NULL, NULL, &err, flags);
2146 if (n == NULL)
2147 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002148 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002151}
2152
Guido van Rossuma110aa61994-08-29 12:50:44 +00002153/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002154
Guido van Rossuma110aa61994-08-29 12:50:44 +00002155node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002156PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 perrdetail err;
2159 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2160 start, &err, flags);
2161 if (n == NULL)
2162 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002163 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002165}
2166
2167node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002168PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 perrdetail err;
2172 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2173 &_PyParser_Grammar, 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;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002178}
2179
2180node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002181PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002184}
2185
Guido van Rossum66ebd912003-04-17 16:02:26 +00002186/* May want to move a more generalized form of this to parsetok.c or
2187 even parser modules. */
2188
2189void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002190PyParser_ClearError(perrdetail *err)
2191{
2192 err_free(err);
2193}
2194
2195void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002196PyParser_SetError(perrdetail *err)
2197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002199}
2200
Victor Stinner7f2fee32011-04-05 00:39:01 +02002201static void
2202err_free(perrdetail *err)
2203{
2204 Py_CLEAR(err->filename);
2205}
2206
Guido van Rossuma110aa61994-08-29 12:50:44 +00002207/* Set the error appropriate to the given input error code (see errcode.h) */
2208
2209static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002210err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 PyObject *v, *w, *errtype, *errtext;
2213 PyObject *msg_obj = NULL;
2214 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 errtype = PyExc_SyntaxError;
2217 switch (err->error) {
2218 case E_ERROR:
2219 return;
2220 case E_SYNTAX:
2221 errtype = PyExc_IndentationError;
2222 if (err->expected == INDENT)
2223 msg = "expected an indented block";
2224 else if (err->token == INDENT)
2225 msg = "unexpected indent";
2226 else if (err->token == DEDENT)
2227 msg = "unexpected unindent";
2228 else {
2229 errtype = PyExc_SyntaxError;
2230 msg = "invalid syntax";
2231 }
2232 break;
2233 case E_TOKEN:
2234 msg = "invalid token";
2235 break;
2236 case E_EOFS:
2237 msg = "EOF while scanning triple-quoted string literal";
2238 break;
2239 case E_EOLS:
2240 msg = "EOL while scanning string literal";
2241 break;
2242 case E_INTR:
2243 if (!PyErr_Occurred())
2244 PyErr_SetNone(PyExc_KeyboardInterrupt);
2245 goto cleanup;
2246 case E_NOMEM:
2247 PyErr_NoMemory();
2248 goto cleanup;
2249 case E_EOF:
2250 msg = "unexpected EOF while parsing";
2251 break;
2252 case E_TABSPACE:
2253 errtype = PyExc_TabError;
2254 msg = "inconsistent use of tabs and spaces in indentation";
2255 break;
2256 case E_OVERFLOW:
2257 msg = "expression too long";
2258 break;
2259 case E_DEDENT:
2260 errtype = PyExc_IndentationError;
2261 msg = "unindent does not match any outer indentation level";
2262 break;
2263 case E_TOODEEP:
2264 errtype = PyExc_IndentationError;
2265 msg = "too many levels of indentation";
2266 break;
2267 case E_DECODE: {
2268 PyObject *type, *value, *tb;
2269 PyErr_Fetch(&type, &value, &tb);
2270 msg = "unknown decode error";
2271 if (value != NULL)
2272 msg_obj = PyObject_Str(value);
2273 Py_XDECREF(type);
2274 Py_XDECREF(value);
2275 Py_XDECREF(tb);
2276 break;
2277 }
2278 case E_LINECONT:
2279 msg = "unexpected character after line continuation character";
2280 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 case E_IDENTIFIER:
2283 msg = "invalid character in identifier";
2284 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002285 case E_BADSINGLE:
2286 msg = "multiple statements found while compiling a single statement";
2287 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 default:
2289 fprintf(stderr, "error=%d\n", err->error);
2290 msg = "unknown parsing error";
2291 break;
2292 }
2293 /* err->text may not be UTF-8 in case of decoding errors.
2294 Explicitly convert to an object. */
2295 if (!err->text) {
2296 errtext = Py_None;
2297 Py_INCREF(Py_None);
2298 } else {
2299 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2300 "replace");
2301 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002302 v = Py_BuildValue("(OiiN)", err->filename,
2303 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 if (v != NULL) {
2305 if (msg_obj)
2306 w = Py_BuildValue("(OO)", msg_obj, v);
2307 else
2308 w = Py_BuildValue("(sO)", msg, v);
2309 } else
2310 w = NULL;
2311 Py_XDECREF(v);
2312 PyErr_SetObject(errtype, w);
2313 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002314cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 Py_XDECREF(msg_obj);
2316 if (err->text != NULL) {
2317 PyObject_FREE(err->text);
2318 err->text = NULL;
2319 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002320}
2321
2322/* Print fatal error message and abort */
2323
2324void
Tim Peters7c321a82002-07-09 02:57:01 +00002325Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002326{
Victor Stinner024e37a2011-03-31 01:31:06 +02002327 const int fd = fileno(stderr);
2328 PyThreadState *tstate;
2329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 fprintf(stderr, "Fatal Python error: %s\n", msg);
2331 fflush(stderr); /* it helps in Windows debug build */
2332 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002333 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002335 else {
2336 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2337 if (tstate != NULL) {
2338 fputc('\n', stderr);
2339 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002340 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002341 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002342 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002343 }
2344
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002345#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 {
2347 size_t len = strlen(msg);
2348 WCHAR* buffer;
2349 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 /* Convert the message to wchar_t. This uses a simple one-to-one
2352 conversion, assuming that the this error message actually uses ASCII
2353 only. If this ceases to be true, we will have to convert. */
2354 buffer = alloca( (len+1) * (sizeof *buffer));
2355 for( i=0; i<=len; ++i)
2356 buffer[i] = msg[i];
2357 OutputDebugStringW(L"Fatal Python error: ");
2358 OutputDebugStringW(buffer);
2359 OutputDebugStringW(L"\n");
2360 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002361#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002363#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002364#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002366}
2367
2368/* Clean up and exit */
2369
Guido van Rossuma110aa61994-08-29 12:50:44 +00002370#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002371#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002372#endif
2373
Collin Winter670e6922007-03-21 02:57:17 +00002374static void (*pyexitfunc)(void) = NULL;
2375/* For the atexit module. */
2376void _Py_PyAtExit(void (*func)(void))
2377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002379}
2380
2381static void
2382call_py_exitfuncs(void)
2383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 if (pyexitfunc == NULL)
2385 return;
Collin Winter670e6922007-03-21 02:57:17 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 (*pyexitfunc)();
2388 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002389}
2390
Antoine Pitrou011bd622009-10-20 21:52:47 +00002391/* Wait until threading._shutdown completes, provided
2392 the threading module was imported in the first place.
2393 The shutdown routine will wait until all non-daemon
2394 "threading" threads have completed. */
2395static void
2396wait_for_thread_shutdown(void)
2397{
2398#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002399 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 PyObject *result;
2401 PyThreadState *tstate = PyThreadState_GET();
2402 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2403 "threading");
2404 if (threading == NULL) {
2405 /* threading not imported */
2406 PyErr_Clear();
2407 return;
2408 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002409 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 if (result == NULL) {
2411 PyErr_WriteUnraisable(threading);
2412 }
2413 else {
2414 Py_DECREF(result);
2415 }
2416 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002417#endif
2418}
2419
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002420#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002421static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002422static int nexitfuncs = 0;
2423
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002424int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 if (nexitfuncs >= NEXITFUNCS)
2427 return -1;
2428 exitfuncs[nexitfuncs++] = func;
2429 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002430}
2431
Guido van Rossumcc283f51997-08-05 02:22:03 +00002432static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002433call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 while (nexitfuncs > 0)
2436 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 fflush(stdout);
2439 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002440}
2441
2442void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002443Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002448}
2449
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002450static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002451initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002452{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002453#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002455#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002456#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002458#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002459#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002461#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002463}
2464
Guido van Rossum7433b121997-02-14 19:45:36 +00002465
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002466/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2467 *
2468 * All of the code in this function must only use async-signal-safe functions,
2469 * listed at `man 7 signal` or
2470 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2471 */
2472void
2473_Py_RestoreSignals(void)
2474{
2475#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002477#endif
2478#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002480#endif
2481#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002483#endif
2484}
2485
2486
Guido van Rossum7433b121997-02-14 19:45:36 +00002487/*
2488 * The file descriptor fd is considered ``interactive'' if either
2489 * a) isatty(fd) is TRUE, or
2490 * b) the -i flag was given, and the filename associated with
2491 * the descriptor is NULL or "<stdin>" or "???".
2492 */
2493int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002494Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 if (isatty((int)fileno(fp)))
2497 return 1;
2498 if (!Py_InteractiveFlag)
2499 return 0;
2500 return (filename == NULL) ||
2501 (strcmp(filename, "<stdin>") == 0) ||
2502 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002503}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002504
2505
Tim Petersd08e3822003-04-17 15:24:21 +00002506#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002507#if defined(WIN32) && defined(_MSC_VER)
2508
2509/* Stack checking for Microsoft C */
2510
2511#include <malloc.h>
2512#include <excpt.h>
2513
Fred Drakee8de31c2000-08-31 05:38:39 +00002514/*
2515 * Return non-zero when we run out of memory on the stack; zero otherwise.
2516 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002517int
Fred Drake399739f2000-08-31 05:52:44 +00002518PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 __try {
2521 /* alloca throws a stack overflow exception if there's
2522 not enough space left on the stack */
2523 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2524 return 0;
2525 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2526 EXCEPTION_EXECUTE_HANDLER :
2527 EXCEPTION_CONTINUE_SEARCH) {
2528 int errcode = _resetstkoflw();
2529 if (errcode == 0)
2530 {
2531 Py_FatalError("Could not reset the stack!");
2532 }
2533 }
2534 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002535}
2536
2537#endif /* WIN32 && _MSC_VER */
2538
2539/* Alternate implementations can be added here... */
2540
2541#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002542
2543
2544/* Wrappers around sigaction() or signal(). */
2545
2546PyOS_sighandler_t
2547PyOS_getsig(int sig)
2548{
2549#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 struct sigaction context;
2551 if (sigaction(sig, NULL, &context) == -1)
2552 return SIG_ERR;
2553 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002554#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002556/* Special signal handling for the secure CRT in Visual Studio 2005 */
2557#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 switch (sig) {
2559 /* Only these signals are valid */
2560 case SIGINT:
2561 case SIGILL:
2562 case SIGFPE:
2563 case SIGSEGV:
2564 case SIGTERM:
2565 case SIGBREAK:
2566 case SIGABRT:
2567 break;
2568 /* Don't call signal() with other values or it will assert */
2569 default:
2570 return SIG_ERR;
2571 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002572#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 handler = signal(sig, SIG_IGN);
2574 if (handler != SIG_ERR)
2575 signal(sig, handler);
2576 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002577#endif
2578}
2579
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002580/*
2581 * All of the code in this function must only use async-signal-safe functions,
2582 * listed at `man 7 signal` or
2583 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2584 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002585PyOS_sighandler_t
2586PyOS_setsig(int sig, PyOS_sighandler_t handler)
2587{
2588#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 /* Some code in Modules/signalmodule.c depends on sigaction() being
2590 * used here if HAVE_SIGACTION is defined. Fix that if this code
2591 * changes to invalidate that assumption.
2592 */
2593 struct sigaction context, ocontext;
2594 context.sa_handler = handler;
2595 sigemptyset(&context.sa_mask);
2596 context.sa_flags = 0;
2597 if (sigaction(sig, &context, &ocontext) == -1)
2598 return SIG_ERR;
2599 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002600#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 PyOS_sighandler_t oldhandler;
2602 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002603#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002605#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002606 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002607#endif
2608}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002609
2610/* Deprecated C API functions still provided for binary compatiblity */
2611
2612#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002613PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002614PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002617}
2618
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002619#undef PyParser_SimpleParseString
2620PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002621PyParser_SimpleParseString(const char *str, int start)
2622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002624}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002625
2626#undef PyRun_AnyFile
2627PyAPI_FUNC(int)
2628PyRun_AnyFile(FILE *fp, const char *name)
2629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002631}
2632
2633#undef PyRun_AnyFileEx
2634PyAPI_FUNC(int)
2635PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002638}
2639
2640#undef PyRun_AnyFileFlags
2641PyAPI_FUNC(int)
2642PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002645}
2646
2647#undef PyRun_File
2648PyAPI_FUNC(PyObject *)
2649PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002652}
2653
2654#undef PyRun_FileEx
2655PyAPI_FUNC(PyObject *)
2656PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002659}
2660
2661#undef PyRun_FileFlags
2662PyAPI_FUNC(PyObject *)
2663PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002667}
2668
2669#undef PyRun_SimpleFile
2670PyAPI_FUNC(int)
2671PyRun_SimpleFile(FILE *f, const char *p)
2672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002674}
2675
2676#undef PyRun_SimpleFileEx
2677PyAPI_FUNC(int)
2678PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002681}
2682
2683
2684#undef PyRun_String
2685PyAPI_FUNC(PyObject *)
2686PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002689}
2690
2691#undef PyRun_SimpleString
2692PyAPI_FUNC(int)
2693PyRun_SimpleString(const char *s)
2694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002696}
2697
2698#undef Py_CompileString
2699PyAPI_FUNC(PyObject *)
2700Py_CompileString(const char *str, const char *p, int s)
2701{
Georg Brandl8334fd92010-12-04 10:26:46 +00002702 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2703}
2704
2705#undef Py_CompileStringFlags
2706PyAPI_FUNC(PyObject *)
2707Py_CompileStringFlags(const char *str, const char *p, int s,
2708 PyCompilerFlags *flags)
2709{
2710 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002711}
2712
2713#undef PyRun_InteractiveOne
2714PyAPI_FUNC(int)
2715PyRun_InteractiveOne(FILE *f, const char *p)
2716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002718}
2719
2720#undef PyRun_InteractiveLoop
2721PyAPI_FUNC(int)
2722PyRun_InteractiveLoop(FILE *f, const char *p)
2723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002725}
2726
2727#ifdef __cplusplus
2728}
2729#endif