blob: 94175be87e95476d43a2c78eed8d17a14eb07a23 [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
Ezio Melotti1f8898a2013-03-26 01:59:56 +020038#ifdef Py_REF_DEBUG
Antoine Pitrou208ac5c2013-04-24 20:17:53 +020039static
40void _print_total_refs(void) {
Ezio Melotti1f8898a2013-03-26 01:59:56 +020041 PyObject *xoptions, *key, *value;
42 xoptions = PySys_GetXOptions();
43 if (xoptions == NULL)
44 return;
45 key = PyUnicode_FromString("showrefcount");
46 if (key == NULL)
47 return;
48 value = PyDict_GetItem(xoptions, key);
49 Py_DECREF(key);
50 if (value == Py_True)
51 fprintf(stderr,
52 "[%" PY_FORMAT_SIZE_T "d refs, "
53 "%" PY_FORMAT_SIZE_T "d blocks]\n",
54 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
55}
56#endif
57
Neal Norwitz4281cef2006-03-04 19:58:13 +000058#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000059#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000060#else /* Py_REF_DEBUG */
Ezio Melotti1f8898a2013-03-26 01:59:56 +020061#define PRINT_TOTAL_REFS() _print_total_refs()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000062#endif
63
64#ifdef __cplusplus
65extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000066#endif
67
Martin v. Löwis790465f2008-04-05 20:41:37 +000068extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000069
Guido van Rossum82598051997-03-05 00:20:32 +000070extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000071
Guido van Rossumb73cc041993-11-01 16:28:59 +000072/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100073static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020074static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000075static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000076static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000077static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000078static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000080static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000082static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020083static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000084static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000085static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000086static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000087static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +020088extern int _PyUnicode_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000089extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000090extern int _PyLong_Init(void);
91extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020092extern int _PyFaulthandler_Init(void);
93extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000094
Mark Hammond8d98d2c2003-04-19 15:41:53 +000095#ifdef WITH_THREAD
96extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
97extern void _PyGILState_Fini(void);
98#endif /* WITH_THREAD */
99
Guido van Rossum82598051997-03-05 00:20:32 +0000100int Py_DebugFlag; /* Needed by parser.c */
101int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000102int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000103int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200104int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000105int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000106int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000107int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000108int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000109int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000110int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000111int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000112int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100113int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000114
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200115PyThreadState *_Py_Finalizing = NULL;
116
Christian Heimes33fe8092008-04-13 13:53:33 +0000117/* PyModule_GetWarningsModule is no longer necessary as of 2.6
118since _warnings is builtin. This API should not be used. */
119PyObject *
120PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000123}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000124
Guido van Rossum25ce5661997-08-02 03:10:38 +0000125static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000126
Thomas Wouters7e474022000-07-16 12:04:32 +0000127/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000128
129int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000130Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000133}
134
Guido van Rossum25ce5661997-08-02 03:10:38 +0000135/* Global initializations. Can be undone by Py_Finalize(). Don't
136 call this twice without an intervening Py_Finalize() call. When
137 initializations fail, a fatal error is issued and the function does
138 not return. On return, the first thread and interpreter state have
139 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000140
Guido van Rossum25ce5661997-08-02 03:10:38 +0000141 Locking: you must hold the interpreter lock while calling this.
142 (If the lock has not yet been initialized, that's equivalent to
143 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000144
Guido van Rossum25ce5661997-08-02 03:10:38 +0000145*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000146
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000147static int
148add_flag(int flag, const char *envs)
149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 int env = atoi(envs);
151 if (flag < env)
152 flag = env;
153 if (flag < 1)
154 flag = 1;
155 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000156}
157
Christian Heimes5833a2f2008-10-30 21:40:04 +0000158static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000159get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000160{
Victor Stinner94908bb2010-08-18 21:23:25 +0000161 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000162 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200163 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000164
Victor Stinner94908bb2010-08-18 21:23:25 +0000165 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 if (!codec)
167 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000168
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200169 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 Py_CLEAR(codec);
171 if (!name)
172 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000173
Victor Stinner94908bb2010-08-18 21:23:25 +0000174 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100175 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000176 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000177 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000179 if (name_str == NULL) {
180 PyErr_NoMemory();
181 return NULL;
182 }
183 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000184
185error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000187 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000189}
Victor Stinner94908bb2010-08-18 21:23:25 +0000190
Victor Stinner94908bb2010-08-18 21:23:25 +0000191static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200192get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000193{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200194#ifdef MS_WINDOWS
195 char codepage[100];
196 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
197 return get_codec_name(codepage);
198#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000199 char* codeset = nl_langinfo(CODESET);
200 if (!codeset || codeset[0] == '\0') {
201 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
202 return NULL;
203 }
204 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200205#else
206 PyErr_SetNone(PyExc_NotImplementedError);
207 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000208#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200209}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000210
Brett Cannonfd074152012-04-14 14:10:13 -0400211static void
212import_init(PyInterpreterState *interp, PyObject *sysmod)
213{
214 PyObject *importlib;
215 PyObject *impmod;
216 PyObject *sys_modules;
217 PyObject *value;
218
219 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400220 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
221 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
222 }
223 else if (Py_VerboseFlag) {
224 PySys_FormatStderr("import _frozen_importlib # frozen\n");
225 }
226 importlib = PyImport_AddModule("_frozen_importlib");
227 if (importlib == NULL) {
228 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
229 "sys.modules");
230 }
231 interp->importlib = importlib;
232 Py_INCREF(interp->importlib);
233
234 /* Install _importlib as __import__ */
235 impmod = PyInit_imp();
236 if (impmod == NULL) {
237 Py_FatalError("Py_Initialize: can't import imp");
238 }
239 else if (Py_VerboseFlag) {
240 PySys_FormatStderr("import imp # builtin\n");
241 }
242 sys_modules = PyImport_GetModuleDict();
243 if (Py_VerboseFlag) {
244 PySys_FormatStderr("import sys # builtin\n");
245 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400246 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
247 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400248 }
249
Brett Cannone0d88a12012-04-25 20:54:04 -0400250 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400251 if (value == NULL) {
252 PyErr_Print();
253 Py_FatalError("Py_Initialize: importlib install failed");
254 }
255 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400256 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400257
258 _PyImportZip_Init();
259}
260
261
Guido van Rossuma027efa1997-05-05 20:56:21 +0000262void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200263_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 PyInterpreterState *interp;
266 PyThreadState *tstate;
267 PyObject *bimod, *sysmod, *pstderr;
268 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (initialized)
272 return;
273 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200274 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000275
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000276#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 /* Set up the LC_CTYPE locale, so we can obtain
278 the locale's charset without having to switch
279 locales. */
280 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000281#endif
282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
284 Py_DebugFlag = add_flag(Py_DebugFlag, p);
285 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
286 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
287 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
288 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
289 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
290 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100291 /* The variable is only tested for existence here; _PyRandom_Init will
292 check its value further. */
293 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
294 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
295
296 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 interp = PyInterpreterState_New();
299 if (interp == NULL)
300 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 tstate = PyThreadState_New(interp);
303 if (tstate == NULL)
304 Py_FatalError("Py_Initialize: can't make first thread");
305 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000306
Victor Stinner6961bd62010-08-17 22:26:51 +0000307#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000308 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
309 destroying the GIL might fail when it is being referenced from
310 another running thread (see issue #9901).
311 Instead we destroy the previously created GIL here, which ensures
312 that we can call Py_Initialize / Py_Finalize multiple times. */
313 _PyEval_FiniThreads();
314
315 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000316 _PyGILState_Init(interp, tstate);
317#endif /* WITH_THREAD */
318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 if (!_PyFrame_Init())
322 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if (!_PyLong_Init())
325 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 if (!PyByteArray_Init())
328 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 interp->modules = PyDict_New();
333 if (interp->modules == NULL)
334 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200337 if (_PyUnicode_Init() < 0)
338 Py_FatalError("Py_Initialize: can't initialize unicode");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 bimod = _PyBuiltin_Init();
341 if (bimod == NULL)
342 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000343 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 interp->builtins = PyModule_GetDict(bimod);
345 if (interp->builtins == NULL)
346 Py_FatalError("Py_Initialize: can't initialize builtins dict");
347 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400350 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 sysmod = _PySys_Init();
353 if (sysmod == NULL)
354 Py_FatalError("Py_Initialize: can't initialize sys");
355 interp->sysdict = PyModule_GetDict(sysmod);
356 if (interp->sysdict == NULL)
357 Py_FatalError("Py_Initialize: can't initialize sys dict");
358 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000359 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PySys_SetPath(Py_GetPath());
361 PyDict_SetItemString(interp->sysdict, "modules",
362 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 /* Set up a preliminary stderr printer until we have enough
365 infrastructure for the io module in place. */
366 pstderr = PyFile_NewStdPrinter(fileno(stderr));
367 if (pstderr == NULL)
368 Py_FatalError("Py_Initialize: can't set preliminary stderr");
369 PySys_SetObject("stderr", pstderr);
370 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000371 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000376
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000377 /* Initialize _warnings. */
378 _PyWarnings_Init();
379
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200380 if (!install_importlib)
381 return;
382
Brett Cannonfd074152012-04-14 14:10:13 -0400383 import_init(interp, sysmod);
384
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200385 /* initialize the faulthandler module */
386 if (_PyFaulthandler_Init())
387 Py_FatalError("Py_Initialize: can't initialize faulthandler");
388
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000389 _PyTime_Init();
390
Victor Stinner793b5312011-04-27 00:24:21 +0200391 if (initfsencoding(interp) < 0)
392 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (install_sigs)
395 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000396
Nick Coghlan85e729e2012-07-15 18:09:52 +1000397 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 if (initstdio() < 0)
399 Py_FatalError(
400 "Py_Initialize: can't initialize sys standard streams");
401
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000402 /* Initialize warnings. */
403 if (PySys_HasWarnOptions()) {
404 PyObject *warnings_module = PyImport_ImportModule("warnings");
405 if (warnings_module == NULL) {
406 fprintf(stderr, "'import warnings' failed; traceback:\n");
407 PyErr_Print();
408 }
409 Py_XDECREF(warnings_module);
410 }
411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (!Py_NoSiteFlag)
413 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000414}
415
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000416void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200417Py_InitializeEx(int install_sigs)
418{
419 _Py_InitializeEx_Private(install_sigs, 1);
420}
421
422void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000423Py_Initialize(void)
424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000426}
427
428
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000429#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000430extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000431#endif
432
Guido van Rossume8432ac2007-07-09 15:04:50 +0000433/* Flush stdout and stderr */
434
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100435static int
436file_is_closed(PyObject *fobj)
437{
438 int r;
439 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
440 if (tmp == NULL) {
441 PyErr_Clear();
442 return 0;
443 }
444 r = PyObject_IsTrue(tmp);
445 Py_DECREF(tmp);
446 if (r < 0)
447 PyErr_Clear();
448 return r > 0;
449}
450
Neal Norwitz2bad9702007-08-27 06:19:22 +0000451static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000452flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 PyObject *fout = PySys_GetObject("stdout");
455 PyObject *ferr = PySys_GetObject("stderr");
456 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200457 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000458
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100459 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200460 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000462 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 else
464 Py_DECREF(tmp);
465 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000466
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100467 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200468 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (tmp == NULL)
470 PyErr_Clear();
471 else
472 Py_DECREF(tmp);
473 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000474}
475
Guido van Rossum25ce5661997-08-02 03:10:38 +0000476/* Undo the effect of Py_Initialize().
477
478 Beware: if multiple interpreter and/or thread states exist, these
479 are not wiped out; only the current thread and interpreter state
480 are deleted. But since everything else is deleted, those other
481 interpreter and thread states should no longer be used.
482
483 (XXX We should do better, e.g. wipe out all interpreters and
484 threads.)
485
486 Locking: as above.
487
488*/
489
490void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000491Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 PyInterpreterState *interp;
494 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (!initialized)
497 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 /* The interpreter is still entirely intact at this point, and the
502 * exit funcs may be relying on that. In particular, if some thread
503 * or exit func is still waiting to do an import, the import machinery
504 * expects Py_IsInitialized() to return true. So don't say the
505 * interpreter is uninitialized until after the exit funcs have run.
506 * Note that Threading.py uses an exit func to do a join on all the
507 * threads created thru it, so this also protects pending imports in
508 * the threads created via Threading.
509 */
510 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 /* Get current thread state and interpreter pointer */
513 tstate = PyThreadState_GET();
514 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000515
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200516 /* Remaining threads (e.g. daemon threads) will automatically exit
517 after taking the GIL (in PyEval_RestoreThread()). */
518 _Py_Finalizing = tstate;
519 initialized = 0;
520
521 /* Flush stdout+stderr */
522 flush_std_files();
523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 /* Disable signal handling */
525 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 /* Collect garbage. This may call finalizers; it's nice to call these
528 * before all modules are destroyed.
529 * XXX If a __del__ or weakref callback is triggered here, and tries to
530 * XXX import a module, bad things can happen, because Python no
531 * XXX longer believes it's initialized.
532 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
533 * XXX is easy to provoke that way. I've also seen, e.g.,
534 * XXX Exception exceptions.ImportError: 'No module named sha'
535 * XXX in <function callback at 0x008F5718> ignored
536 * XXX but I'm unclear on exactly how that one happens. In any case,
537 * XXX I haven't seen a real-life report of either of these.
538 */
539 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000540#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 /* With COUNT_ALLOCS, it helps to run GC multiple times:
542 each collection might release some types from the type
543 list, so they become garbage. */
544 while (PyGC_Collect() > 0)
545 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000546#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 /* Destroy all modules */
548 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 /* Flush stdout+stderr (again, in case more was printed) */
551 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100554 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 * XXX This is disabled because it caused too many problems. If
556 * XXX a __del__ or weakref callback triggers here, Python code has
557 * XXX a hard time running, because even the sys module has been
558 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
559 * XXX One symptom is a sequence of information-free messages
560 * XXX coming from threads (if a __del__ or callback is invoked,
561 * XXX other threads can execute too, and any exception they encounter
562 * XXX triggers a comedy of errors as subsystem after subsystem
563 * XXX fails to find what it *expects* to find in sys to help report
564 * XXX the exception and consequent unexpected failures). I've also
565 * XXX seen segfaults then, after adding print statements to the
566 * XXX Python code getting called.
567 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000568#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000570#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
573 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000574
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200575 /* Cleanup typeobject.c's internal caches. */
576 _PyType_Fini();
577
Victor Stinner024e37a2011-03-31 01:31:06 +0200578 /* unload faulthandler module */
579 _PyFaulthandler_Fini();
580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000582#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000584#endif
585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000587
Tim Peters9cf25ce2003-04-17 15:21:01 +0000588#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 /* Display all objects still alive -- this can invoke arbitrary
590 * __repr__ overrides, so requires a mostly-intact interpreter.
591 * Alas, a lot of stuff may still be alive now that will be cleaned
592 * up later.
593 */
594 if (Py_GETENV("PYTHONDUMPREFS"))
595 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000596#endif /* Py_TRACE_REFS */
597
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200598 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 /* Now we decref the exception classes. After this point nothing
602 can raise an exception. That's okay, because each Fini() method
603 below has been checked to make sure no exceptions are ever
604 raised.
605 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 /* Sundry finalizers */
610 PyMethod_Fini();
611 PyFrame_Fini();
612 PyCFunction_Fini();
613 PyTuple_Fini();
614 PyList_Fini();
615 PySet_Fini();
616 PyBytes_Fini();
617 PyByteArray_Fini();
618 PyLong_Fini();
619 PyFloat_Fini();
620 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100621 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200622 _PyGC_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 /* Cleanup Unicode implementation */
625 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000628 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 free((char*)Py_FileSystemDefaultEncoding);
630 Py_FileSystemDefaultEncoding = NULL;
631 }
Christian Heimesc8967002007-11-30 10:18:26 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 /* XXX Still allocated:
634 - various static ad-hoc pointers to interned strings
635 - int and float free list blocks
636 - whatever various modules and libraries allocate
637 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000640
Victor Stinner51fa4582013-07-07 15:50:49 +0200641 /* Cleanup auto-thread-state */
642#ifdef WITH_THREAD
643 _PyGILState_Fini();
644#endif /* WITH_THREAD */
645
646 /* Delete current thread. After this, many C API calls become crashy. */
647 PyThreadState_Swap(NULL);
648 PyInterpreterState_Delete(interp);
649
Tim Peters269b2a62003-04-17 19:52:29 +0000650#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 /* Display addresses (& refcnts) of all objects still alive.
652 * An address can be used to find the repr of the object, printed
653 * above by _Py_PrintReferences.
654 */
655 if (Py_GETENV("PYTHONDUMPREFS"))
656 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000657#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000658#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400660 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000661#endif
662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000664}
665
666/* Create and initialize a new interpreter and thread, and return the
667 new thread. This requires that Py_Initialize() has been called
668 first.
669
670 Unsuccessful initialization yields a NULL pointer. Note that *no*
671 exception information is available even in this case -- the
672 exception information is held in the thread, and there is no
673 thread.
674
675 Locking: as above.
676
677*/
678
679PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000680Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 PyInterpreterState *interp;
683 PyThreadState *tstate, *save_tstate;
684 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 if (!initialized)
687 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 interp = PyInterpreterState_New();
690 if (interp == NULL)
691 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 tstate = PyThreadState_New(interp);
694 if (tstate == NULL) {
695 PyInterpreterState_Delete(interp);
696 return NULL;
697 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000704
Victor Stinner49d3f252010-10-17 01:24:53 +0000705 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (bimod != NULL) {
707 interp->builtins = PyModule_GetDict(bimod);
708 if (interp->builtins == NULL)
709 goto handle_error;
710 Py_INCREF(interp->builtins);
711 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400714 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000715
Victor Stinner49d3f252010-10-17 01:24:53 +0000716 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 if (bimod != NULL && sysmod != NULL) {
718 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 interp->sysdict = PyModule_GetDict(sysmod);
721 if (interp->sysdict == NULL)
722 goto handle_error;
723 Py_INCREF(interp->sysdict);
724 PySys_SetPath(Py_GetPath());
725 PyDict_SetItemString(interp->sysdict, "modules",
726 interp->modules);
727 /* Set up a preliminary stderr printer until we have enough
728 infrastructure for the io module in place. */
729 pstderr = PyFile_NewStdPrinter(fileno(stderr));
730 if (pstderr == NULL)
731 Py_FatalError("Py_Initialize: can't set preliminary stderr");
732 PySys_SetObject("stderr", pstderr);
733 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000734 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200737
Brett Cannonfd074152012-04-14 14:10:13 -0400738 import_init(interp, sysmod);
739
Victor Stinner793b5312011-04-27 00:24:21 +0200740 if (initfsencoding(interp) < 0)
741 goto handle_error;
742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (initstdio() < 0)
744 Py_FatalError(
745 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000746 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (!Py_NoSiteFlag)
748 initsite();
749 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (!PyErr_Occurred())
752 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000753
Thomas Wouters89f507f2006-12-13 04:49:30 +0000754handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000756
Victor Stinnerc40a3502011-04-27 00:20:27 +0200757 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyThreadState_Clear(tstate);
759 PyThreadState_Swap(save_tstate);
760 PyThreadState_Delete(tstate);
761 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000764}
765
766/* Delete an interpreter and its last thread. This requires that the
767 given thread state is current, that the thread has no remaining
768 frames, and that it is its interpreter's only remaining thread.
769 It is a fatal error to violate these constraints.
770
771 (Py_Finalize() doesn't have these constraints -- it zaps
772 everything, regardless.)
773
774 Locking: as above.
775
776*/
777
778void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000779Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (tstate != PyThreadState_GET())
784 Py_FatalError("Py_EndInterpreter: thread is not current");
785 if (tstate->frame != NULL)
786 Py_FatalError("Py_EndInterpreter: thread still has a frame");
787 if (tstate != interp->tstate_head || tstate->next != NULL)
788 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 PyImport_Cleanup();
791 PyInterpreterState_Clear(interp);
792 PyThreadState_Swap(NULL);
793 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000794}
795
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200796#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000797static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200798#else
799static wchar_t *progname = L"python3";
800#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000801
802void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000803Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 if (pn && *pn)
806 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000807}
808
Martin v. Löwis790465f2008-04-05 20:41:37 +0000809wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000810Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000813}
814
Martin v. Löwis790465f2008-04-05 20:41:37 +0000815static wchar_t *default_home = NULL;
816static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000817
818void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000819Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000822}
823
Martin v. Löwis790465f2008-04-05 20:41:37 +0000824wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000825Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 wchar_t *home = default_home;
828 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
829 char* chome = Py_GETENV("PYTHONHOME");
830 if (chome) {
831 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
832 if (r != (size_t)-1 && r <= PATH_MAX)
833 home = env_home;
834 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 }
837 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000838}
839
Guido van Rossum6135a871995-01-09 17:53:26 +0000840/* Create __main__ module */
841
842static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000843initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000844{
Brett Cannon13853a62013-05-04 17:37:09 -0400845 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 m = PyImport_AddModule("__main__");
847 if (m == NULL)
848 Py_FatalError("can't create __main__ module");
849 d = PyModule_GetDict(m);
850 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
851 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000852 if (bimod == NULL) {
853 Py_FatalError("Failed to retrieve builtins module");
854 }
855 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
856 Py_FatalError("Failed to initialize __main__.__builtins__");
857 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 Py_DECREF(bimod);
859 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000860 /* Main is a little special - imp.is_builtin("__main__") will return
861 * False, but BuiltinImporter is still the most appropriate initial
862 * setting for its __loader__ attribute. A more suitable value will
863 * be set if __main__ gets further initialized later in the startup
864 * process.
865 */
Brett Cannon13853a62013-05-04 17:37:09 -0400866 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400867 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000868 PyObject *loader = PyObject_GetAttrString(interp->importlib,
869 "BuiltinImporter");
870 if (loader == NULL) {
871 Py_FatalError("Failed to retrieve BuiltinImporter");
872 }
873 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
874 Py_FatalError("Failed to initialize __main__.__loader__");
875 }
876 Py_DECREF(loader);
877 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000878}
879
Victor Stinner793b5312011-04-27 00:24:21 +0200880static int
881initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000882{
883 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000884
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200885 if (Py_FileSystemDefaultEncoding == NULL)
886 {
887 Py_FileSystemDefaultEncoding = get_locale_encoding();
888 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000889 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000890
Victor Stinnere4743092010-10-19 00:05:51 +0000891 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200892 interp->fscodec_initialized = 1;
893 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000894 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000895
896 /* the encoding is mbcs, utf-8 or ascii */
897 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
898 if (!codec) {
899 /* Such error can only occurs in critical situations: no more
900 * memory, import a module of the standard library failed,
901 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200902 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000903 }
Victor Stinner793b5312011-04-27 00:24:21 +0200904 Py_DECREF(codec);
905 interp->fscodec_initialized = 1;
906 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000907}
908
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000909/* Import the site module (not into __main__ though) */
910
911static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000912initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 PyObject *m;
915 m = PyImport_ImportModule("site");
916 if (m == NULL) {
917 PyErr_Print();
918 Py_Finalize();
919 exit(1);
920 }
921 else {
922 Py_DECREF(m);
923 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000924}
925
Antoine Pitrou05608432009-01-09 18:53:14 +0000926static PyObject*
927create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 int fd, int write_mode, char* name,
929 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
932 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000933 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject *line_buffering;
935 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200936 _Py_IDENTIFIER(open);
937 _Py_IDENTIFIER(isatty);
938 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200939 _Py_IDENTIFIER(name);
940 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* stdin is always opened in buffered mode, first because it shouldn't
943 make a difference in common use cases, second because TextIOWrapper
944 depends on the presence of a read1() method which only exists on
945 buffered streams.
946 */
947 if (Py_UnbufferedStdioFlag && write_mode)
948 buffering = 0;
949 else
950 buffering = -1;
951 if (write_mode)
952 mode = "wb";
953 else
954 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200955 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
956 fd, mode, buffering,
957 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 if (buf == NULL)
959 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200962 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200963 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 if (raw == NULL)
965 goto error;
966 }
967 else {
968 raw = buf;
969 Py_INCREF(raw);
970 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200973 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200975 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (res == NULL)
977 goto error;
978 isatty = PyObject_IsTrue(res);
979 Py_DECREF(res);
980 if (isatty == -1)
981 goto error;
982 if (isatty || Py_UnbufferedStdioFlag)
983 line_buffering = Py_True;
984 else
985 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 Py_CLEAR(raw);
988 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000989
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000990#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +0200991 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
992 newlines to "\n".
993 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
994 newline = NULL;
995#else
996 /* sys.stdin: split lines at "\n".
997 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
998 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000999#endif
1000
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001001 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1002 buf, encoding, errors,
1003 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 Py_CLEAR(buf);
1005 if (stream == NULL)
1006 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (write_mode)
1009 mode = "w";
1010 else
1011 mode = "r";
1012 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001013 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 goto error;
1015 Py_CLEAR(text);
1016 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001017
1018error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 Py_XDECREF(buf);
1020 Py_XDECREF(stream);
1021 Py_XDECREF(text);
1022 Py_XDECREF(raw);
1023 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001024}
1025
Antoine Pitrou11942a52011-11-28 19:08:36 +01001026static int
1027is_valid_fd(int fd)
1028{
1029 int dummy_fd;
1030 if (fd < 0 || !_PyVerify_fd(fd))
1031 return 0;
1032 dummy_fd = dup(fd);
1033 if (dummy_fd < 0)
1034 return 0;
1035 close(dummy_fd);
1036 return 1;
1037}
1038
Georg Brandl1a3284e2007-12-02 09:40:06 +00001039/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001040static int
1041initstdio(void)
1042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 PyObject *iomod = NULL, *wrapper;
1044 PyObject *bimod = NULL;
1045 PyObject *m;
1046 PyObject *std = NULL;
1047 int status = 0, fd;
1048 PyObject * encoding_attr;
1049 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 /* Hack to avoid a nasty recursion issue when Python is invoked
1052 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1053 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1054 goto error;
1055 }
1056 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1059 goto error;
1060 }
1061 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 if (!(bimod = PyImport_ImportModule("builtins"))) {
1064 goto error;
1065 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 if (!(iomod = PyImport_ImportModule("io"))) {
1068 goto error;
1069 }
1070 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1071 goto error;
1072 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 /* Set builtins.open */
1075 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001076 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 goto error;
1078 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001079 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 encoding = Py_GETENV("PYTHONIOENCODING");
1082 errors = NULL;
1083 if (encoding) {
1084 encoding = strdup(encoding);
1085 errors = strchr(encoding, ':');
1086 if (errors) {
1087 *errors = '\0';
1088 errors++;
1089 }
1090 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 /* Set sys.stdin */
1093 fd = fileno(stdin);
1094 /* Under some conditions stdin, stdout and stderr may not be connected
1095 * and fileno() may point to an invalid file descriptor. For example
1096 * GUI apps don't have valid standard streams by default.
1097 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001098 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 std = Py_None;
1100 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 }
1102 else {
1103 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1104 if (std == NULL)
1105 goto error;
1106 } /* if (fd < 0) */
1107 PySys_SetObject("__stdin__", std);
1108 PySys_SetObject("stdin", std);
1109 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 /* Set sys.stdout */
1112 fd = fileno(stdout);
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, "<stdout>", encoding, errors);
1119 if (std == NULL)
1120 goto error;
1121 } /* if (fd < 0) */
1122 PySys_SetObject("__stdout__", std);
1123 PySys_SetObject("stdout", std);
1124 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001125
Guido van Rossum98297ee2007-11-06 21:34:58 +00001126#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 /* Set sys.stderr, replaces the preliminary stderr */
1128 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001129 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 std = Py_None;
1131 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 }
1133 else {
1134 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1135 if (std == NULL)
1136 goto error;
1137 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 /* Same as hack above, pre-import stderr's codec to avoid recursion
1140 when import.c tries to write to stderr in verbose mode. */
1141 encoding_attr = PyObject_GetAttrString(std, "encoding");
1142 if (encoding_attr != NULL) {
1143 const char * encoding;
1144 encoding = _PyUnicode_AsString(encoding_attr);
1145 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001146 PyObject *codec_info = _PyCodec_Lookup(encoding);
1147 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001149 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 }
1151 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 PySys_SetObject("__stderr__", std);
1154 PySys_SetObject("stderr", std);
1155 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001156#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001159 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 status = -1;
1161 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (encoding)
1164 free(encoding);
1165 Py_XDECREF(bimod);
1166 Py_XDECREF(iomod);
1167 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001168}
1169
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001170/* Parse input from a file and execute it */
1171
1172int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001173PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 if (filename == NULL)
1177 filename = "???";
1178 if (Py_FdIsInteractive(fp, filename)) {
1179 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1180 if (closeit)
1181 fclose(fp);
1182 return err;
1183 }
1184 else
1185 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001186}
1187
1188int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001189PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 PyObject *v;
1192 int ret;
1193 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 if (flags == NULL) {
1196 flags = &local_flags;
1197 local_flags.cf_flags = 0;
1198 }
1199 v = PySys_GetObject("ps1");
1200 if (v == NULL) {
1201 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1202 Py_XDECREF(v);
1203 }
1204 v = PySys_GetObject("ps2");
1205 if (v == NULL) {
1206 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1207 Py_XDECREF(v);
1208 }
1209 for (;;) {
1210 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1211 PRINT_TOTAL_REFS();
1212 if (ret == E_EOF)
1213 return 0;
1214 /*
1215 if (ret == E_NOMEM)
1216 return -1;
1217 */
1218 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001219}
1220
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001221/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001222static int PARSER_FLAGS(PyCompilerFlags *flags)
1223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 int parser_flags = 0;
1225 if (!flags)
1226 return 0;
1227 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1228 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1229 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1230 parser_flags |= PyPARSE_IGNORE_COOKIE;
1231 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1232 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1233 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001234}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001235
Thomas Wouters89f507f2006-12-13 04:49:30 +00001236#if 0
1237/* Keep an example of flags with future keyword support. */
1238#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1240 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1241 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1242 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001243#endif
1244
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001245int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001246PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 PyObject *m, *d, *v, *w, *oenc = NULL;
1249 mod_ty mod;
1250 PyArena *arena;
1251 char *ps1 = "", *ps2 = "", *enc = NULL;
1252 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001253 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001256 /* Fetch encoding from sys.stdin if possible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 v = PySys_GetObject("stdin");
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001258 if (v && v != Py_None) {
1259 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1260 if (oenc)
1261 enc = _PyUnicode_AsString(oenc);
1262 if (!enc)
1263 PyErr_Clear();
1264 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 }
1266 v = PySys_GetObject("ps1");
1267 if (v != NULL) {
1268 v = PyObject_Str(v);
1269 if (v == NULL)
1270 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001271 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001273 if (ps1 == NULL) {
1274 PyErr_Clear();
1275 ps1 = "";
1276 }
1277 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 }
1279 w = PySys_GetObject("ps2");
1280 if (w != NULL) {
1281 w = PyObject_Str(w);
1282 if (w == NULL)
1283 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001284 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001286 if (ps2 == NULL) {
1287 PyErr_Clear();
1288 ps2 = "";
1289 }
1290 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 }
1292 arena = PyArena_New();
1293 if (arena == NULL) {
1294 Py_XDECREF(v);
1295 Py_XDECREF(w);
1296 Py_XDECREF(oenc);
1297 return -1;
1298 }
1299 mod = PyParser_ASTFromFile(fp, filename, enc,
1300 Py_single_input, ps1, ps2,
1301 flags, &errcode, arena);
1302 Py_XDECREF(v);
1303 Py_XDECREF(w);
1304 Py_XDECREF(oenc);
1305 if (mod == NULL) {
1306 PyArena_Free(arena);
1307 if (errcode == E_EOF) {
1308 PyErr_Clear();
1309 return E_EOF;
1310 }
1311 PyErr_Print();
1312 return -1;
1313 }
1314 m = PyImport_AddModule("__main__");
1315 if (m == NULL) {
1316 PyArena_Free(arena);
1317 return -1;
1318 }
1319 d = PyModule_GetDict(m);
1320 v = run_mod(mod, filename, d, d, flags, arena);
1321 PyArena_Free(arena);
1322 flush_io();
1323 if (v == NULL) {
1324 PyErr_Print();
1325 return -1;
1326 }
1327 Py_DECREF(v);
1328 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001329}
1330
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001331/* Check whether a file maybe a pyc file: Look at the extension,
1332 the file type, and, if we may close it, at the first few bytes. */
1333
1334static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001335maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1338 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* Only look into the file if we are allowed to close it, since
1341 it then should also be seekable. */
1342 if (closeit) {
1343 /* Read only two bytes of the magic. If the file was opened in
1344 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1345 be read as they are on disk. */
1346 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1347 unsigned char buf[2];
1348 /* Mess: In case of -x, the stream is NOT at its start now,
1349 and ungetc() was used to push back the first newline,
1350 which makes the current stream position formally undefined,
1351 and a x-platform nightmare.
1352 Unfortunately, we have no direct way to know whether -x
1353 was specified. So we use a terrible hack: if the current
1354 stream position is not 0, we assume -x was specified, and
1355 give up. Bug 132850 on SourceForge spells out the
1356 hopelessness of trying anything else (fseek and ftell
1357 don't work predictably x-platform for text-mode files).
1358 */
1359 int ispyc = 0;
1360 if (ftell(fp) == 0) {
1361 if (fread(buf, 1, 2, fp) == 2 &&
1362 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1363 ispyc = 1;
1364 rewind(fp);
1365 }
1366 return ispyc;
1367 }
1368 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001369}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001370
Guido van Rossum0df002c2000-08-27 19:21:52 +00001371int
Nick Coghlanceda83c2012-07-15 23:18:08 +10001372static set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001373{
1374 PyInterpreterState *interp;
1375 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001376 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001377 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001378
1379 filename_obj = PyUnicode_DecodeFSDefault(filename);
1380 if (filename_obj == NULL)
1381 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001382 /* Get current thread state and interpreter pointer */
1383 tstate = PyThreadState_GET();
1384 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001385 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1386 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001387 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001388 return -1;
1389 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001390 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001391 Py_DECREF(loader_type);
1392 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001393 return -1;
1394 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001395 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1396 result = -1;
1397 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001398 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001399 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001400}
1401
1402int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001403PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 PyObject *m, *d, *v;
1407 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001408 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001409 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 m = PyImport_AddModule("__main__");
1412 if (m == NULL)
1413 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001414 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 d = PyModule_GetDict(m);
1416 if (PyDict_GetItemString(d, "__file__") == NULL) {
1417 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001418 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001420 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1422 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001423 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001425 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1426 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001427 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001428 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 set_file_name = 1;
1430 Py_DECREF(f);
1431 }
1432 len = strlen(filename);
1433 ext = filename + len - (len > 4 ? 4 : 0);
1434 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001435 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 /* Try to run a pyc file. First, re-open in binary */
1437 if (closeit)
1438 fclose(fp);
Christian Heimes04ac4c12012-09-11 15:47:28 +02001439 if ((pyc_fp = fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 goto done;
1442 }
1443 /* Turn on optimization if a .pyo file is given */
1444 if (strcmp(ext, ".pyo") == 0)
1445 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001446
1447 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1448 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1449 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001450 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001451 goto done;
1452 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001453 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1454 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001456 /* When running from stdin, leave __main__.__loader__ alone */
1457 if (strcmp(filename, "<stdin>") != 0 &&
1458 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1459 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1460 ret = -1;
1461 goto done;
1462 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1464 closeit, flags);
1465 }
1466 flush_io();
1467 if (v == NULL) {
1468 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 goto done;
1470 }
1471 Py_DECREF(v);
1472 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001473 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1475 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001476 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001478}
1479
1480int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001481PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 PyObject *m, *d, *v;
1484 m = PyImport_AddModule("__main__");
1485 if (m == NULL)
1486 return -1;
1487 d = PyModule_GetDict(m);
1488 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1489 if (v == NULL) {
1490 PyErr_Print();
1491 return -1;
1492 }
1493 Py_DECREF(v);
1494 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001495}
1496
Barry Warsaw035574d1997-08-29 22:07:17 +00001497static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001498parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 long hold;
1502 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001503 _Py_IDENTIFIER(msg);
1504 _Py_IDENTIFIER(filename);
1505 _Py_IDENTIFIER(lineno);
1506 _Py_IDENTIFIER(offset);
1507 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001508
Benjamin Peterson80d50422012-04-03 00:30:38 -04001509 *message = NULL;
1510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001512 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001513 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001515
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001516 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001517 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001519 if (v == Py_None) {
1520 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001522 }
1523 else {
1524 *filename = _PyUnicode_AsString(v);
1525 Py_DECREF(v);
1526 if (!*filename)
1527 goto finally;
1528 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001529
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001530 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001531 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 goto finally;
1533 hold = PyLong_AsLong(v);
1534 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (hold < 0 && PyErr_Occurred())
1536 goto finally;
1537 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001538
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001539 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001540 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 goto finally;
1542 if (v == Py_None) {
1543 *offset = -1;
1544 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 } else {
1546 hold = PyLong_AsLong(v);
1547 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 if (hold < 0 && PyErr_Occurred())
1549 goto finally;
1550 *offset = (int)hold;
1551 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001552
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001553 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001554 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001556 if (v == Py_None) {
1557 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001559 }
1560 else {
1561 *text = _PyUnicode_AsString(v);
1562 Py_DECREF(v);
1563 if (!*text)
1564 goto finally;
1565 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001567
1568finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001569 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001571}
1572
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001573void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001574PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001577}
1578
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001579static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001580print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 char *nl;
1583 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001584 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1585 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 for (;;) {
1587 nl = strchr(text, '\n');
1588 if (nl == NULL || nl-text >= offset)
1589 break;
1590 offset -= (int)(nl+1-text);
1591 text = nl+1;
1592 }
1593 while (*text == ' ' || *text == '\t') {
1594 text++;
1595 offset--;
1596 }
1597 }
1598 PyFile_WriteString(" ", f);
1599 PyFile_WriteString(text, f);
1600 if (*text == '\0' || text[strlen(text)-1] != '\n')
1601 PyFile_WriteString("\n", f);
1602 if (offset == -1)
1603 return;
1604 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001605 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001608}
1609
Guido van Rossum66e8e862001-03-23 17:54:43 +00001610static void
1611handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 PyObject *exception, *value, *tb;
1614 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 if (Py_InspectFlag)
1617 /* Don't exit if -i flag was given. This flag is set to 0
1618 * when entering interactive mode for inspecting. */
1619 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 PyErr_Fetch(&exception, &value, &tb);
1622 fflush(stdout);
1623 if (value == NULL || value == Py_None)
1624 goto done;
1625 if (PyExceptionInstance_Check(value)) {
1626 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001627 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001628 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 if (code) {
1630 Py_DECREF(value);
1631 value = code;
1632 if (value == Py_None)
1633 goto done;
1634 }
1635 /* If we failed to dig out the 'code' attribute,
1636 just let the else clause below print the error. */
1637 }
1638 if (PyLong_Check(value))
1639 exitcode = (int)PyLong_AsLong(value);
1640 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001641 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001642 if (sys_stderr != NULL && sys_stderr != Py_None) {
1643 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1644 } else {
1645 PyObject_Print(value, stderr, Py_PRINT_RAW);
1646 fflush(stderr);
1647 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 PySys_WriteStderr("\n");
1649 exitcode = 1;
1650 }
Tim Peterscf615b52003-04-19 18:47:02 +00001651 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 /* Restore and clear the exception info, in order to properly decref
1653 * the exception, value, and traceback. If we just exit instead,
1654 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1655 * some finalizers from running.
1656 */
1657 PyErr_Restore(exception, value, tb);
1658 PyErr_Clear();
1659 Py_Exit(exitcode);
1660 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001661}
1662
1663void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001664PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1669 handle_system_exit();
1670 }
1671 PyErr_Fetch(&exception, &v, &tb);
1672 if (exception == NULL)
1673 return;
1674 PyErr_NormalizeException(&exception, &v, &tb);
1675 if (tb == NULL) {
1676 tb = Py_None;
1677 Py_INCREF(tb);
1678 }
1679 PyException_SetTraceback(v, tb);
1680 if (exception == NULL)
1681 return;
1682 /* Now we know v != NULL too */
1683 if (set_sys_last_vars) {
1684 PySys_SetObject("last_type", exception);
1685 PySys_SetObject("last_value", v);
1686 PySys_SetObject("last_traceback", tb);
1687 }
1688 hook = PySys_GetObject("excepthook");
1689 if (hook) {
1690 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1691 PyObject *result = PyEval_CallObject(hook, args);
1692 if (result == NULL) {
1693 PyObject *exception2, *v2, *tb2;
1694 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1695 handle_system_exit();
1696 }
1697 PyErr_Fetch(&exception2, &v2, &tb2);
1698 PyErr_NormalizeException(&exception2, &v2, &tb2);
1699 /* It should not be possible for exception2 or v2
1700 to be NULL. However PyErr_Display() can't
1701 tolerate NULLs, so just be safe. */
1702 if (exception2 == NULL) {
1703 exception2 = Py_None;
1704 Py_INCREF(exception2);
1705 }
1706 if (v2 == NULL) {
1707 v2 = Py_None;
1708 Py_INCREF(v2);
1709 }
1710 fflush(stdout);
1711 PySys_WriteStderr("Error in sys.excepthook:\n");
1712 PyErr_Display(exception2, v2, tb2);
1713 PySys_WriteStderr("\nOriginal exception was:\n");
1714 PyErr_Display(exception, v, tb);
1715 Py_DECREF(exception2);
1716 Py_DECREF(v2);
1717 Py_XDECREF(tb2);
1718 }
1719 Py_XDECREF(result);
1720 Py_XDECREF(args);
1721 } else {
1722 PySys_WriteStderr("sys.excepthook is missing\n");
1723 PyErr_Display(exception, v, tb);
1724 }
1725 Py_XDECREF(exception);
1726 Py_XDECREF(v);
1727 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001728}
1729
Benjamin Petersone6528212008-07-15 15:32:09 +00001730static void
1731print_exception(PyObject *f, PyObject *value)
1732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 int err = 0;
1734 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001735 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 if (!PyExceptionInstance_Check(value)) {
1738 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1739 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1740 PyFile_WriteString(" found\n", f);
1741 return;
1742 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 Py_INCREF(value);
1745 fflush(stdout);
1746 type = (PyObject *) Py_TYPE(value);
1747 tb = PyException_GetTraceback(value);
1748 if (tb && tb != Py_None)
1749 err = PyTraceBack_Print(tb, f);
1750 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001751 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 {
1753 PyObject *message;
1754 const char *filename, *text;
1755 int lineno, offset;
1756 if (!parse_syntax_error(value, &message, &filename,
1757 &lineno, &offset, &text))
1758 PyErr_Clear();
1759 else {
1760 char buf[10];
1761 PyFile_WriteString(" File \"", f);
1762 if (filename == NULL)
1763 PyFile_WriteString("<string>", f);
1764 else
1765 PyFile_WriteString(filename, f);
1766 PyFile_WriteString("\", line ", f);
1767 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1768 PyFile_WriteString(buf, f);
1769 PyFile_WriteString("\n", f);
1770 if (text != NULL)
1771 print_error_text(f, offset, text);
1772 Py_DECREF(value);
1773 value = message;
1774 /* Can't be bothered to check all those
1775 PyFile_WriteString() calls */
1776 if (PyErr_Occurred())
1777 err = -1;
1778 }
1779 }
1780 if (err) {
1781 /* Don't do anything else */
1782 }
1783 else {
1784 PyObject* moduleName;
1785 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001786 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 assert(PyExceptionClass_Check(type));
1788 className = PyExceptionClass_Name(type);
1789 if (className != NULL) {
1790 char *dot = strrchr(className, '.');
1791 if (dot != NULL)
1792 className = dot+1;
1793 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001794
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001795 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1797 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001798 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 err = PyFile_WriteString("<unknown>", f);
1800 }
1801 else {
1802 char* modstr = _PyUnicode_AsString(moduleName);
1803 if (modstr && strcmp(modstr, "builtins"))
1804 {
1805 err = PyFile_WriteString(modstr, f);
1806 err += PyFile_WriteString(".", f);
1807 }
1808 Py_DECREF(moduleName);
1809 }
1810 if (err == 0) {
1811 if (className == NULL)
1812 err = PyFile_WriteString("<unknown>", f);
1813 else
1814 err = PyFile_WriteString(className, f);
1815 }
1816 }
1817 if (err == 0 && (value != Py_None)) {
1818 PyObject *s = PyObject_Str(value);
1819 /* only print colon if the str() of the
1820 object is not the empty string
1821 */
1822 if (s == NULL)
1823 err = -1;
1824 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001825 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 err = PyFile_WriteString(": ", f);
1827 if (err == 0)
1828 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1829 Py_XDECREF(s);
1830 }
1831 /* try to write a newline in any case */
1832 err += PyFile_WriteString("\n", f);
1833 Py_XDECREF(tb);
1834 Py_DECREF(value);
1835 /* If an error happened here, don't show it.
1836 XXX This is wrong, but too many callers rely on this behavior. */
1837 if (err != 0)
1838 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001839}
1840
1841static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 "\nThe above exception was the direct cause "
1843 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001844
1845static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 "\nDuring handling of the above exception, "
1847 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001848
1849static void
1850print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001852 int err = 0, res;
1853 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 if (seen != NULL) {
1856 /* Exception chaining */
1857 if (PySet_Add(seen, value) == -1)
1858 PyErr_Clear();
1859 else if (PyExceptionInstance_Check(value)) {
1860 cause = PyException_GetCause(value);
1861 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001862 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 res = PySet_Contains(seen, cause);
1864 if (res == -1)
1865 PyErr_Clear();
1866 if (res == 0) {
1867 print_exception_recursive(
1868 f, cause, seen);
1869 err |= PyFile_WriteString(
1870 cause_message, f);
1871 }
1872 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001873 else if (context &&
1874 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 res = PySet_Contains(seen, context);
1876 if (res == -1)
1877 PyErr_Clear();
1878 if (res == 0) {
1879 print_exception_recursive(
1880 f, context, seen);
1881 err |= PyFile_WriteString(
1882 context_message, f);
1883 }
1884 }
1885 Py_XDECREF(context);
1886 Py_XDECREF(cause);
1887 }
1888 }
1889 print_exception(f, value);
1890 if (err != 0)
1891 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001892}
1893
Thomas Wouters477c8d52006-05-27 19:21:47 +00001894void
1895PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 PyObject *seen;
1898 PyObject *f = PySys_GetObject("stderr");
1899 if (f == Py_None) {
1900 /* pass */
1901 }
1902 else if (f == NULL) {
1903 _PyObject_Dump(value);
1904 fprintf(stderr, "lost sys.stderr\n");
1905 }
1906 else {
1907 /* We choose to ignore seen being possibly NULL, and report
1908 at least the main exception (it could be a MemoryError).
1909 */
1910 seen = PySet_New(NULL);
1911 if (seen == NULL)
1912 PyErr_Clear();
1913 print_exception_recursive(f, value, seen);
1914 Py_XDECREF(seen);
1915 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001916}
1917
Guido van Rossum82598051997-03-05 00:20:32 +00001918PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001919PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 PyObject *ret = NULL;
1923 mod_ty mod;
1924 PyArena *arena = PyArena_New();
1925 if (arena == NULL)
1926 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1929 if (mod != NULL)
1930 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1931 PyArena_Free(arena);
1932 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001933}
1934
1935PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001936PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 PyObject *ret;
1940 mod_ty mod;
1941 PyArena *arena = PyArena_New();
1942 if (arena == NULL)
1943 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1946 flags, NULL, arena);
1947 if (closeit)
1948 fclose(fp);
1949 if (mod == NULL) {
1950 PyArena_Free(arena);
1951 return NULL;
1952 }
1953 ret = run_mod(mod, filename, globals, locals, flags, arena);
1954 PyArena_Free(arena);
1955 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001956}
1957
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001958static void
1959flush_io(void)
1960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 PyObject *f, *r;
1962 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001963 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 /* Save the current exception */
1966 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 f = PySys_GetObject("stderr");
1969 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001970 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (r)
1972 Py_DECREF(r);
1973 else
1974 PyErr_Clear();
1975 }
1976 f = PySys_GetObject("stdout");
1977 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001978 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 if (r)
1980 Py_DECREF(r);
1981 else
1982 PyErr_Clear();
1983 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001986}
1987
Guido van Rossum82598051997-03-05 00:20:32 +00001988static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001991{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 PyCodeObject *co;
1993 PyObject *v;
1994 co = PyAST_Compile(mod, filename, flags, arena);
1995 if (co == NULL)
1996 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001997 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 Py_DECREF(co);
1999 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002000}
2001
Guido van Rossum82598051997-03-05 00:20:32 +00002002static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002003run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 PyCodeObject *co;
2007 PyObject *v;
2008 long magic;
2009 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002010
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 magic = PyMarshal_ReadLongFromFile(fp);
2012 if (magic != PyImport_GetMagicNumber()) {
2013 PyErr_SetString(PyExc_RuntimeError,
2014 "Bad magic number in .pyc file");
2015 return NULL;
2016 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002017 /* Skip mtime and size */
2018 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 (void) PyMarshal_ReadLongFromFile(fp);
2020 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 if (v == NULL || !PyCode_Check(v)) {
2022 Py_XDECREF(v);
2023 PyErr_SetString(PyExc_RuntimeError,
2024 "Bad code object in .pyc file");
2025 return NULL;
2026 }
2027 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002028 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 if (v && flags)
2030 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2031 Py_DECREF(co);
2032 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002033}
2034
Guido van Rossum82598051997-03-05 00:20:32 +00002035PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00002036Py_CompileStringExFlags(const char *str, const char *filename, int start,
2037 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 PyCodeObject *co;
2040 mod_ty mod;
2041 PyArena *arena = PyArena_New();
2042 if (arena == NULL)
2043 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
2046 if (mod == NULL) {
2047 PyArena_Free(arena);
2048 return NULL;
2049 }
2050 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2051 PyObject *result = PyAST_mod2obj(mod);
2052 PyArena_Free(arena);
2053 return result;
2054 }
Georg Brandl8334fd92010-12-04 10:26:46 +00002055 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 PyArena_Free(arena);
2057 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002058}
2059
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002060/* For use in Py_LIMITED_API */
2061#undef Py_CompileString
2062PyObject *
2063PyCompileString(const char *str, const char *filename, int start)
2064{
2065 return Py_CompileStringFlags(str, filename, start, NULL);
2066}
2067
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002068struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002069Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 struct symtable *st;
2072 mod_ty mod;
2073 PyCompilerFlags flags;
2074 PyArena *arena = PyArena_New();
2075 if (arena == NULL)
2076 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 flags.cf_flags = 0;
2079 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
2080 if (mod == NULL) {
2081 PyArena_Free(arena);
2082 return NULL;
2083 }
2084 st = PySymtable_Build(mod, filename, 0);
2085 PyArena_Free(arena);
2086 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002087}
2088
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002089/* Preferred access to parser is through AST. */
2090mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002091PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 mod_ty mod;
2095 PyCompilerFlags localflags;
2096 perrdetail err;
2097 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
2100 &_PyParser_Grammar, start, &err,
2101 &iflags);
2102 if (flags == NULL) {
2103 localflags.cf_flags = 0;
2104 flags = &localflags;
2105 }
2106 if (n) {
2107 flags->cf_flags |= iflags & PyCF_MASK;
2108 mod = PyAST_FromNode(n, flags, filename, arena);
2109 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 }
2111 else {
2112 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002113 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002115 err_free(&err);
2116 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002117}
2118
2119mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00002120PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 int start, char *ps1,
2122 char *ps2, PyCompilerFlags *flags, int *errcode,
2123 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 mod_ty mod;
2126 PyCompilerFlags localflags;
2127 perrdetail err;
2128 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
2131 &_PyParser_Grammar,
2132 start, ps1, ps2, &err, &iflags);
2133 if (flags == NULL) {
2134 localflags.cf_flags = 0;
2135 flags = &localflags;
2136 }
2137 if (n) {
2138 flags->cf_flags |= iflags & PyCF_MASK;
2139 mod = PyAST_FromNode(n, flags, filename, arena);
2140 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 }
2142 else {
2143 err_input(&err);
2144 if (errcode)
2145 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002146 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002148 err_free(&err);
2149 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002150}
2151
Guido van Rossuma110aa61994-08-29 12:50:44 +00002152/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002153
Guido van Rossuma110aa61994-08-29 12:50:44 +00002154node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002155PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 perrdetail err;
2158 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2159 &_PyParser_Grammar,
2160 start, NULL, NULL, &err, flags);
2161 if (n == NULL)
2162 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002163 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002166}
2167
Guido van Rossuma110aa61994-08-29 12:50:44 +00002168/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002169
Guido van Rossuma110aa61994-08-29 12:50:44 +00002170node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002171PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 perrdetail err;
2174 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2175 start, &err, flags);
2176 if (n == NULL)
2177 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002178 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002180}
2181
2182node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002183PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 perrdetail err;
2187 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2188 &_PyParser_Grammar, start, &err, flags);
2189 if (n == NULL)
2190 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002191 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002193}
2194
2195node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002196PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002199}
2200
Guido van Rossum66ebd912003-04-17 16:02:26 +00002201/* May want to move a more generalized form of this to parsetok.c or
2202 even parser modules. */
2203
2204void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002205PyParser_ClearError(perrdetail *err)
2206{
2207 err_free(err);
2208}
2209
2210void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002211PyParser_SetError(perrdetail *err)
2212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002214}
2215
Victor Stinner7f2fee32011-04-05 00:39:01 +02002216static void
2217err_free(perrdetail *err)
2218{
2219 Py_CLEAR(err->filename);
2220}
2221
Guido van Rossuma110aa61994-08-29 12:50:44 +00002222/* Set the error appropriate to the given input error code (see errcode.h) */
2223
2224static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002225err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 PyObject *v, *w, *errtype, *errtext;
2228 PyObject *msg_obj = NULL;
2229 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 errtype = PyExc_SyntaxError;
2232 switch (err->error) {
2233 case E_ERROR:
2234 return;
2235 case E_SYNTAX:
2236 errtype = PyExc_IndentationError;
2237 if (err->expected == INDENT)
2238 msg = "expected an indented block";
2239 else if (err->token == INDENT)
2240 msg = "unexpected indent";
2241 else if (err->token == DEDENT)
2242 msg = "unexpected unindent";
2243 else {
2244 errtype = PyExc_SyntaxError;
2245 msg = "invalid syntax";
2246 }
2247 break;
2248 case E_TOKEN:
2249 msg = "invalid token";
2250 break;
2251 case E_EOFS:
2252 msg = "EOF while scanning triple-quoted string literal";
2253 break;
2254 case E_EOLS:
2255 msg = "EOL while scanning string literal";
2256 break;
2257 case E_INTR:
2258 if (!PyErr_Occurred())
2259 PyErr_SetNone(PyExc_KeyboardInterrupt);
2260 goto cleanup;
2261 case E_NOMEM:
2262 PyErr_NoMemory();
2263 goto cleanup;
2264 case E_EOF:
2265 msg = "unexpected EOF while parsing";
2266 break;
2267 case E_TABSPACE:
2268 errtype = PyExc_TabError;
2269 msg = "inconsistent use of tabs and spaces in indentation";
2270 break;
2271 case E_OVERFLOW:
2272 msg = "expression too long";
2273 break;
2274 case E_DEDENT:
2275 errtype = PyExc_IndentationError;
2276 msg = "unindent does not match any outer indentation level";
2277 break;
2278 case E_TOODEEP:
2279 errtype = PyExc_IndentationError;
2280 msg = "too many levels of indentation";
2281 break;
2282 case E_DECODE: {
2283 PyObject *type, *value, *tb;
2284 PyErr_Fetch(&type, &value, &tb);
2285 msg = "unknown decode error";
2286 if (value != NULL)
2287 msg_obj = PyObject_Str(value);
2288 Py_XDECREF(type);
2289 Py_XDECREF(value);
2290 Py_XDECREF(tb);
2291 break;
2292 }
2293 case E_LINECONT:
2294 msg = "unexpected character after line continuation character";
2295 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 case E_IDENTIFIER:
2298 msg = "invalid character in identifier";
2299 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002300 case E_BADSINGLE:
2301 msg = "multiple statements found while compiling a single statement";
2302 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 default:
2304 fprintf(stderr, "error=%d\n", err->error);
2305 msg = "unknown parsing error";
2306 break;
2307 }
2308 /* err->text may not be UTF-8 in case of decoding errors.
2309 Explicitly convert to an object. */
2310 if (!err->text) {
2311 errtext = Py_None;
2312 Py_INCREF(Py_None);
2313 } else {
2314 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2315 "replace");
2316 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002317 v = Py_BuildValue("(OiiN)", err->filename,
2318 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 if (v != NULL) {
2320 if (msg_obj)
2321 w = Py_BuildValue("(OO)", msg_obj, v);
2322 else
2323 w = Py_BuildValue("(sO)", msg, v);
2324 } else
2325 w = NULL;
2326 Py_XDECREF(v);
2327 PyErr_SetObject(errtype, w);
2328 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002329cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 Py_XDECREF(msg_obj);
2331 if (err->text != NULL) {
2332 PyObject_FREE(err->text);
2333 err->text = NULL;
2334 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002335}
2336
2337/* Print fatal error message and abort */
2338
2339void
Tim Peters7c321a82002-07-09 02:57:01 +00002340Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002341{
Victor Stinner024e37a2011-03-31 01:31:06 +02002342 const int fd = fileno(stderr);
2343 PyThreadState *tstate;
2344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 fprintf(stderr, "Fatal Python error: %s\n", msg);
2346 fflush(stderr); /* it helps in Windows debug build */
2347 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002348 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002350 else {
2351 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2352 if (tstate != NULL) {
2353 fputc('\n', stderr);
2354 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002355 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002356 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002357 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002358 }
2359
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002360#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 {
2362 size_t len = strlen(msg);
2363 WCHAR* buffer;
2364 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 /* Convert the message to wchar_t. This uses a simple one-to-one
2367 conversion, assuming that the this error message actually uses ASCII
2368 only. If this ceases to be true, we will have to convert. */
2369 buffer = alloca( (len+1) * (sizeof *buffer));
2370 for( i=0; i<=len; ++i)
2371 buffer[i] = msg[i];
2372 OutputDebugStringW(L"Fatal Python error: ");
2373 OutputDebugStringW(buffer);
2374 OutputDebugStringW(L"\n");
2375 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002376#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002378#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002379#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002381}
2382
2383/* Clean up and exit */
2384
Guido van Rossuma110aa61994-08-29 12:50:44 +00002385#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002386#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002387#endif
2388
Collin Winter670e6922007-03-21 02:57:17 +00002389static void (*pyexitfunc)(void) = NULL;
2390/* For the atexit module. */
2391void _Py_PyAtExit(void (*func)(void))
2392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002394}
2395
2396static void
2397call_py_exitfuncs(void)
2398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 if (pyexitfunc == NULL)
2400 return;
Collin Winter670e6922007-03-21 02:57:17 +00002401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 (*pyexitfunc)();
2403 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002404}
2405
Antoine Pitrou011bd622009-10-20 21:52:47 +00002406/* Wait until threading._shutdown completes, provided
2407 the threading module was imported in the first place.
2408 The shutdown routine will wait until all non-daemon
2409 "threading" threads have completed. */
2410static void
2411wait_for_thread_shutdown(void)
2412{
2413#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002414 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 PyObject *result;
2416 PyThreadState *tstate = PyThreadState_GET();
2417 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2418 "threading");
2419 if (threading == NULL) {
2420 /* threading not imported */
2421 PyErr_Clear();
2422 return;
2423 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002424 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 if (result == NULL) {
2426 PyErr_WriteUnraisable(threading);
2427 }
2428 else {
2429 Py_DECREF(result);
2430 }
2431 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002432#endif
2433}
2434
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002435#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002436static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002437static int nexitfuncs = 0;
2438
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002439int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 if (nexitfuncs >= NEXITFUNCS)
2442 return -1;
2443 exitfuncs[nexitfuncs++] = func;
2444 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002445}
2446
Guido van Rossumcc283f51997-08-05 02:22:03 +00002447static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002448call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 while (nexitfuncs > 0)
2451 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 fflush(stdout);
2454 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002455}
2456
2457void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002458Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002463}
2464
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002465static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002466initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002467{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002468#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002470#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002471#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002473#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002474#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002476#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002478}
2479
Guido van Rossum7433b121997-02-14 19:45:36 +00002480
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002481/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2482 *
2483 * All of the code in this function must only use async-signal-safe functions,
2484 * listed at `man 7 signal` or
2485 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2486 */
2487void
2488_Py_RestoreSignals(void)
2489{
2490#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002492#endif
2493#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002495#endif
2496#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002498#endif
2499}
2500
2501
Guido van Rossum7433b121997-02-14 19:45:36 +00002502/*
2503 * The file descriptor fd is considered ``interactive'' if either
2504 * a) isatty(fd) is TRUE, or
2505 * b) the -i flag was given, and the filename associated with
2506 * the descriptor is NULL or "<stdin>" or "???".
2507 */
2508int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002509Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 if (isatty((int)fileno(fp)))
2512 return 1;
2513 if (!Py_InteractiveFlag)
2514 return 0;
2515 return (filename == NULL) ||
2516 (strcmp(filename, "<stdin>") == 0) ||
2517 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002518}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002519
2520
Tim Petersd08e3822003-04-17 15:24:21 +00002521#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002522#if defined(WIN32) && defined(_MSC_VER)
2523
2524/* Stack checking for Microsoft C */
2525
2526#include <malloc.h>
2527#include <excpt.h>
2528
Fred Drakee8de31c2000-08-31 05:38:39 +00002529/*
2530 * Return non-zero when we run out of memory on the stack; zero otherwise.
2531 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002532int
Fred Drake399739f2000-08-31 05:52:44 +00002533PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 __try {
2536 /* alloca throws a stack overflow exception if there's
2537 not enough space left on the stack */
2538 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2539 return 0;
2540 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2541 EXCEPTION_EXECUTE_HANDLER :
2542 EXCEPTION_CONTINUE_SEARCH) {
2543 int errcode = _resetstkoflw();
2544 if (errcode == 0)
2545 {
2546 Py_FatalError("Could not reset the stack!");
2547 }
2548 }
2549 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002550}
2551
2552#endif /* WIN32 && _MSC_VER */
2553
2554/* Alternate implementations can be added here... */
2555
2556#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002557
2558
2559/* Wrappers around sigaction() or signal(). */
2560
2561PyOS_sighandler_t
2562PyOS_getsig(int sig)
2563{
2564#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 struct sigaction context;
2566 if (sigaction(sig, NULL, &context) == -1)
2567 return SIG_ERR;
2568 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002569#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002571/* Special signal handling for the secure CRT in Visual Studio 2005 */
2572#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 switch (sig) {
2574 /* Only these signals are valid */
2575 case SIGINT:
2576 case SIGILL:
2577 case SIGFPE:
2578 case SIGSEGV:
2579 case SIGTERM:
2580 case SIGBREAK:
2581 case SIGABRT:
2582 break;
2583 /* Don't call signal() with other values or it will assert */
2584 default:
2585 return SIG_ERR;
2586 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002587#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 handler = signal(sig, SIG_IGN);
2589 if (handler != SIG_ERR)
2590 signal(sig, handler);
2591 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002592#endif
2593}
2594
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002595/*
2596 * All of the code in this function must only use async-signal-safe functions,
2597 * listed at `man 7 signal` or
2598 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2599 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002600PyOS_sighandler_t
2601PyOS_setsig(int sig, PyOS_sighandler_t handler)
2602{
2603#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 /* Some code in Modules/signalmodule.c depends on sigaction() being
2605 * used here if HAVE_SIGACTION is defined. Fix that if this code
2606 * changes to invalidate that assumption.
2607 */
2608 struct sigaction context, ocontext;
2609 context.sa_handler = handler;
2610 sigemptyset(&context.sa_mask);
2611 context.sa_flags = 0;
2612 if (sigaction(sig, &context, &ocontext) == -1)
2613 return SIG_ERR;
2614 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002615#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 PyOS_sighandler_t oldhandler;
2617 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002618#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002620#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002622#endif
2623}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002624
2625/* Deprecated C API functions still provided for binary compatiblity */
2626
2627#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002628PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002629PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002632}
2633
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002634#undef PyParser_SimpleParseString
2635PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002636PyParser_SimpleParseString(const char *str, int start)
2637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002639}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002640
2641#undef PyRun_AnyFile
2642PyAPI_FUNC(int)
2643PyRun_AnyFile(FILE *fp, const char *name)
2644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002646}
2647
2648#undef PyRun_AnyFileEx
2649PyAPI_FUNC(int)
2650PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002653}
2654
2655#undef PyRun_AnyFileFlags
2656PyAPI_FUNC(int)
2657PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002660}
2661
2662#undef PyRun_File
2663PyAPI_FUNC(PyObject *)
2664PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002667}
2668
2669#undef PyRun_FileEx
2670PyAPI_FUNC(PyObject *)
2671PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002674}
2675
2676#undef PyRun_FileFlags
2677PyAPI_FUNC(PyObject *)
2678PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002682}
2683
2684#undef PyRun_SimpleFile
2685PyAPI_FUNC(int)
2686PyRun_SimpleFile(FILE *f, const char *p)
2687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002689}
2690
2691#undef PyRun_SimpleFileEx
2692PyAPI_FUNC(int)
2693PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002696}
2697
2698
2699#undef PyRun_String
2700PyAPI_FUNC(PyObject *)
2701PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002704}
2705
2706#undef PyRun_SimpleString
2707PyAPI_FUNC(int)
2708PyRun_SimpleString(const char *s)
2709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002711}
2712
2713#undef Py_CompileString
2714PyAPI_FUNC(PyObject *)
2715Py_CompileString(const char *str, const char *p, int s)
2716{
Georg Brandl8334fd92010-12-04 10:26:46 +00002717 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2718}
2719
2720#undef Py_CompileStringFlags
2721PyAPI_FUNC(PyObject *)
2722Py_CompileStringFlags(const char *str, const char *p, int s,
2723 PyCompilerFlags *flags)
2724{
2725 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002726}
2727
2728#undef PyRun_InteractiveOne
2729PyAPI_FUNC(int)
2730PyRun_InteractiveOne(FILE *f, const char *p)
2731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002733}
2734
2735#undef PyRun_InteractiveLoop
2736PyAPI_FUNC(int)
2737PyRun_InteractiveLoop(FILE *f, const char *p)
2738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002740}
2741
2742#ifdef __cplusplus
2743}
2744#endif