blob: 15a48f9947cff5319e29bfdd2d58b8bb96f3de02 [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);
Victor Stinner26f91992013-07-17 01:22:45 +020089extern int _PyStructSequence_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000090extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000091extern int _PyLong_Init(void);
92extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020093extern int _PyFaulthandler_Init(void);
94extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000095
Mark Hammond8d98d2c2003-04-19 15:41:53 +000096#ifdef WITH_THREAD
97extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
98extern void _PyGILState_Fini(void);
99#endif /* WITH_THREAD */
100
Guido van Rossum82598051997-03-05 00:20:32 +0000101int Py_DebugFlag; /* Needed by parser.c */
102int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000103int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000104int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200105int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000106int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000107int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000108int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000109int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000110int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000111int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000112int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000113int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100114int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200115int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000116
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200117PyThreadState *_Py_Finalizing = NULL;
118
Christian Heimes49e61802013-10-22 10:22:29 +0200119/* Hack to force loading of object files */
120int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
121 PyOS_mystrnicmp; /* Python/pystrcmp.o */
122
Christian Heimes33fe8092008-04-13 13:53:33 +0000123/* PyModule_GetWarningsModule is no longer necessary as of 2.6
124since _warnings is builtin. This API should not be used. */
125PyObject *
126PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000129}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000130
Guido van Rossum25ce5661997-08-02 03:10:38 +0000131static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000132
Thomas Wouters7e474022000-07-16 12:04:32 +0000133/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000134
135int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000136Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000139}
140
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000141/* Helper to allow an embedding application to override the normal
142 * mechanism that attempts to figure out an appropriate IO encoding
143 */
144
145static char *_Py_StandardStreamEncoding = NULL;
146static char *_Py_StandardStreamErrors = NULL;
147
148int
149Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
150{
151 if (Py_IsInitialized()) {
152 /* This is too late to have any effect */
153 return -1;
154 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000155 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
156 * initialised yet.
157 *
158 * However, the raw memory allocators are initialised appropriately
159 * as C static variables, so _PyMem_RawStrdup is OK even though
160 * Py_Initialize hasn't been called yet.
161 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000162 if (encoding) {
163 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
164 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000165 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000166 }
167 }
168 if (errors) {
169 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
170 if (!_Py_StandardStreamErrors) {
171 if (_Py_StandardStreamEncoding) {
172 PyMem_RawFree(_Py_StandardStreamEncoding);
173 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000174 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000175 }
176 }
177 return 0;
178}
179
Guido van Rossum25ce5661997-08-02 03:10:38 +0000180/* Global initializations. Can be undone by Py_Finalize(). Don't
181 call this twice without an intervening Py_Finalize() call. When
182 initializations fail, a fatal error is issued and the function does
183 not return. On return, the first thread and interpreter state have
184 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000185
Guido van Rossum25ce5661997-08-02 03:10:38 +0000186 Locking: you must hold the interpreter lock while calling this.
187 (If the lock has not yet been initialized, that's equivalent to
188 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000189
Guido van Rossum25ce5661997-08-02 03:10:38 +0000190*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000191
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000192static int
193add_flag(int flag, const char *envs)
194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 int env = atoi(envs);
196 if (flag < env)
197 flag = env;
198 if (flag < 1)
199 flag = 1;
200 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000201}
202
Christian Heimes5833a2f2008-10-30 21:40:04 +0000203static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000204get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000205{
Victor Stinner94908bb2010-08-18 21:23:25 +0000206 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000207 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200208 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000209
Victor Stinner94908bb2010-08-18 21:23:25 +0000210 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 if (!codec)
212 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000213
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200214 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 Py_CLEAR(codec);
216 if (!name)
217 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000218
Victor Stinner94908bb2010-08-18 21:23:25 +0000219 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100220 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000221 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200222 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000224 if (name_str == NULL) {
225 PyErr_NoMemory();
226 return NULL;
227 }
228 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000229
230error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000232 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000234}
Victor Stinner94908bb2010-08-18 21:23:25 +0000235
Victor Stinner94908bb2010-08-18 21:23:25 +0000236static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200237get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000238{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200239#ifdef MS_WINDOWS
240 char codepage[100];
241 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
242 return get_codec_name(codepage);
243#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000244 char* codeset = nl_langinfo(CODESET);
245 if (!codeset || codeset[0] == '\0') {
246 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
247 return NULL;
248 }
249 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200250#else
251 PyErr_SetNone(PyExc_NotImplementedError);
252 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000253#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200254}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000255
Brett Cannonfd074152012-04-14 14:10:13 -0400256static void
257import_init(PyInterpreterState *interp, PyObject *sysmod)
258{
259 PyObject *importlib;
260 PyObject *impmod;
261 PyObject *sys_modules;
262 PyObject *value;
263
264 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400265 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
266 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
267 }
268 else if (Py_VerboseFlag) {
269 PySys_FormatStderr("import _frozen_importlib # frozen\n");
270 }
271 importlib = PyImport_AddModule("_frozen_importlib");
272 if (importlib == NULL) {
273 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
274 "sys.modules");
275 }
276 interp->importlib = importlib;
277 Py_INCREF(interp->importlib);
278
279 /* Install _importlib as __import__ */
280 impmod = PyInit_imp();
281 if (impmod == NULL) {
282 Py_FatalError("Py_Initialize: can't import imp");
283 }
284 else if (Py_VerboseFlag) {
285 PySys_FormatStderr("import imp # builtin\n");
286 }
287 sys_modules = PyImport_GetModuleDict();
288 if (Py_VerboseFlag) {
289 PySys_FormatStderr("import sys # builtin\n");
290 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400291 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
292 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400293 }
294
Brett Cannone0d88a12012-04-25 20:54:04 -0400295 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400296 if (value == NULL) {
297 PyErr_Print();
298 Py_FatalError("Py_Initialize: importlib install failed");
299 }
300 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400301 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400302
303 _PyImportZip_Init();
304}
305
306
Guido van Rossuma027efa1997-05-05 20:56:21 +0000307void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200308_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 PyInterpreterState *interp;
311 PyThreadState *tstate;
312 PyObject *bimod, *sysmod, *pstderr;
313 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (initialized)
317 return;
318 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200319 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000320
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000321#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 /* Set up the LC_CTYPE locale, so we can obtain
323 the locale's charset without having to switch
324 locales. */
325 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000326#endif
327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
329 Py_DebugFlag = add_flag(Py_DebugFlag, p);
330 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
331 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
332 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
333 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
334 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
335 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100336 /* The variable is only tested for existence here; _PyRandom_Init will
337 check its value further. */
338 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
339 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
340
341 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 interp = PyInterpreterState_New();
344 if (interp == NULL)
345 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 tstate = PyThreadState_New(interp);
348 if (tstate == NULL)
349 Py_FatalError("Py_Initialize: can't make first thread");
350 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000351
Victor Stinner6961bd62010-08-17 22:26:51 +0000352#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000353 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
354 destroying the GIL might fail when it is being referenced from
355 another running thread (see issue #9901).
356 Instead we destroy the previously created GIL here, which ensures
357 that we can call Py_Initialize / Py_Finalize multiple times. */
358 _PyEval_FiniThreads();
359
360 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000361 _PyGILState_Init(interp, tstate);
362#endif /* WITH_THREAD */
363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (!_PyFrame_Init())
367 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 if (!_PyLong_Init())
370 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 if (!PyByteArray_Init())
373 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000374
Victor Stinner1c8f0592013-07-22 22:24:54 +0200375 if (!_PyFloat_Init())
376 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 interp->modules = PyDict_New();
379 if (interp->modules == NULL)
380 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200383 if (_PyUnicode_Init() < 0)
384 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200385 if (_PyStructSequence_Init() < 0)
386 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 bimod = _PyBuiltin_Init();
389 if (bimod == NULL)
390 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000391 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 interp->builtins = PyModule_GetDict(bimod);
393 if (interp->builtins == NULL)
394 Py_FatalError("Py_Initialize: can't initialize builtins dict");
395 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400398 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 sysmod = _PySys_Init();
401 if (sysmod == NULL)
402 Py_FatalError("Py_Initialize: can't initialize sys");
403 interp->sysdict = PyModule_GetDict(sysmod);
404 if (interp->sysdict == NULL)
405 Py_FatalError("Py_Initialize: can't initialize sys dict");
406 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000407 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PySys_SetPath(Py_GetPath());
409 PyDict_SetItemString(interp->sysdict, "modules",
410 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 /* Set up a preliminary stderr printer until we have enough
413 infrastructure for the io module in place. */
414 pstderr = PyFile_NewStdPrinter(fileno(stderr));
415 if (pstderr == NULL)
416 Py_FatalError("Py_Initialize: can't set preliminary stderr");
417 PySys_SetObject("stderr", pstderr);
418 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000419 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000424
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000425 /* Initialize _warnings. */
426 _PyWarnings_Init();
427
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200428 if (!install_importlib)
429 return;
430
Brett Cannonfd074152012-04-14 14:10:13 -0400431 import_init(interp, sysmod);
432
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200433 /* initialize the faulthandler module */
434 if (_PyFaulthandler_Init())
435 Py_FatalError("Py_Initialize: can't initialize faulthandler");
436
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000437 _PyTime_Init();
438
Victor Stinner793b5312011-04-27 00:24:21 +0200439 if (initfsencoding(interp) < 0)
440 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (install_sigs)
443 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000444
Nick Coghlan85e729e2012-07-15 18:09:52 +1000445 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 if (initstdio() < 0)
447 Py_FatalError(
448 "Py_Initialize: can't initialize sys standard streams");
449
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000450 /* Initialize warnings. */
451 if (PySys_HasWarnOptions()) {
452 PyObject *warnings_module = PyImport_ImportModule("warnings");
453 if (warnings_module == NULL) {
454 fprintf(stderr, "'import warnings' failed; traceback:\n");
455 PyErr_Print();
456 }
457 Py_XDECREF(warnings_module);
458 }
459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (!Py_NoSiteFlag)
461 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000462}
463
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000464void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200465Py_InitializeEx(int install_sigs)
466{
467 _Py_InitializeEx_Private(install_sigs, 1);
468}
469
470void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000471Py_Initialize(void)
472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000474}
475
476
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000477#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000478extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000479#endif
480
Guido van Rossume8432ac2007-07-09 15:04:50 +0000481/* Flush stdout and stderr */
482
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100483static int
484file_is_closed(PyObject *fobj)
485{
486 int r;
487 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
488 if (tmp == NULL) {
489 PyErr_Clear();
490 return 0;
491 }
492 r = PyObject_IsTrue(tmp);
493 Py_DECREF(tmp);
494 if (r < 0)
495 PyErr_Clear();
496 return r > 0;
497}
498
Neal Norwitz2bad9702007-08-27 06:19:22 +0000499static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000500flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 PyObject *fout = PySys_GetObject("stdout");
503 PyObject *ferr = PySys_GetObject("stderr");
504 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200505 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000506
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100507 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200508 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000510 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 else
512 Py_DECREF(tmp);
513 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000514
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100515 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200516 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (tmp == NULL)
518 PyErr_Clear();
519 else
520 Py_DECREF(tmp);
521 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000522}
523
Guido van Rossum25ce5661997-08-02 03:10:38 +0000524/* Undo the effect of Py_Initialize().
525
526 Beware: if multiple interpreter and/or thread states exist, these
527 are not wiped out; only the current thread and interpreter state
528 are deleted. But since everything else is deleted, those other
529 interpreter and thread states should no longer be used.
530
531 (XXX We should do better, e.g. wipe out all interpreters and
532 threads.)
533
534 Locking: as above.
535
536*/
537
538void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000539Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 PyInterpreterState *interp;
542 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (!initialized)
545 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 /* The interpreter is still entirely intact at this point, and the
550 * exit funcs may be relying on that. In particular, if some thread
551 * or exit func is still waiting to do an import, the import machinery
552 * expects Py_IsInitialized() to return true. So don't say the
553 * interpreter is uninitialized until after the exit funcs have run.
554 * Note that Threading.py uses an exit func to do a join on all the
555 * threads created thru it, so this also protects pending imports in
556 * the threads created via Threading.
557 */
558 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 /* Get current thread state and interpreter pointer */
561 tstate = PyThreadState_GET();
562 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000563
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200564 /* Remaining threads (e.g. daemon threads) will automatically exit
565 after taking the GIL (in PyEval_RestoreThread()). */
566 _Py_Finalizing = tstate;
567 initialized = 0;
568
569 /* Flush stdout+stderr */
570 flush_std_files();
571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 /* Disable signal handling */
573 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 /* Collect garbage. This may call finalizers; it's nice to call these
576 * before all modules are destroyed.
577 * XXX If a __del__ or weakref callback is triggered here, and tries to
578 * XXX import a module, bad things can happen, because Python no
579 * XXX longer believes it's initialized.
580 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
581 * XXX is easy to provoke that way. I've also seen, e.g.,
582 * XXX Exception exceptions.ImportError: 'No module named sha'
583 * XXX in <function callback at 0x008F5718> ignored
584 * XXX but I'm unclear on exactly how that one happens. In any case,
585 * XXX I haven't seen a real-life report of either of these.
586 */
587 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000588#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 /* With COUNT_ALLOCS, it helps to run GC multiple times:
590 each collection might release some types from the type
591 list, so they become garbage. */
592 while (PyGC_Collect() > 0)
593 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000594#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 /* Destroy all modules */
596 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 /* Flush stdout+stderr (again, in case more was printed) */
599 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100602 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 * XXX This is disabled because it caused too many problems. If
604 * XXX a __del__ or weakref callback triggers here, Python code has
605 * XXX a hard time running, because even the sys module has been
606 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
607 * XXX One symptom is a sequence of information-free messages
608 * XXX coming from threads (if a __del__ or callback is invoked,
609 * XXX other threads can execute too, and any exception they encounter
610 * XXX triggers a comedy of errors as subsystem after subsystem
611 * XXX fails to find what it *expects* to find in sys to help report
612 * XXX the exception and consequent unexpected failures). I've also
613 * XXX seen segfaults then, after adding print statements to the
614 * XXX Python code getting called.
615 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000616#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000618#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
621 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000622
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200623 /* Cleanup typeobject.c's internal caches. */
624 _PyType_Fini();
625
Victor Stinner024e37a2011-03-31 01:31:06 +0200626 /* unload faulthandler module */
627 _PyFaulthandler_Fini();
628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000630#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000632#endif
633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000635
Tim Peters9cf25ce2003-04-17 15:21:01 +0000636#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 /* Display all objects still alive -- this can invoke arbitrary
638 * __repr__ overrides, so requires a mostly-intact interpreter.
639 * Alas, a lot of stuff may still be alive now that will be cleaned
640 * up later.
641 */
642 if (Py_GETENV("PYTHONDUMPREFS"))
643 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000644#endif /* Py_TRACE_REFS */
645
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200646 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 /* Now we decref the exception classes. After this point nothing
650 can raise an exception. That's okay, because each Fini() method
651 below has been checked to make sure no exceptions are ever
652 raised.
653 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 /* Sundry finalizers */
658 PyMethod_Fini();
659 PyFrame_Fini();
660 PyCFunction_Fini();
661 PyTuple_Fini();
662 PyList_Fini();
663 PySet_Fini();
664 PyBytes_Fini();
665 PyByteArray_Fini();
666 PyLong_Fini();
667 PyFloat_Fini();
668 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100669 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200670 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200671 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 /* Cleanup Unicode implementation */
674 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000677 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200678 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 Py_FileSystemDefaultEncoding = NULL;
680 }
Christian Heimesc8967002007-11-30 10:18:26 +0000681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 /* XXX Still allocated:
683 - various static ad-hoc pointers to interned strings
684 - int and float free list blocks
685 - whatever various modules and libraries allocate
686 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000689
Victor Stinner51fa4582013-07-07 15:50:49 +0200690 /* Cleanup auto-thread-state */
691#ifdef WITH_THREAD
692 _PyGILState_Fini();
693#endif /* WITH_THREAD */
694
695 /* Delete current thread. After this, many C API calls become crashy. */
696 PyThreadState_Swap(NULL);
697 PyInterpreterState_Delete(interp);
698
Tim Peters269b2a62003-04-17 19:52:29 +0000699#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 /* Display addresses (& refcnts) of all objects still alive.
701 * An address can be used to find the repr of the object, printed
702 * above by _Py_PrintReferences.
703 */
704 if (Py_GETENV("PYTHONDUMPREFS"))
705 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000706#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000707#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400709 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000710#endif
711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000713}
714
715/* Create and initialize a new interpreter and thread, and return the
716 new thread. This requires that Py_Initialize() has been called
717 first.
718
719 Unsuccessful initialization yields a NULL pointer. Note that *no*
720 exception information is available even in this case -- the
721 exception information is held in the thread, and there is no
722 thread.
723
724 Locking: as above.
725
726*/
727
728PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000729Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 PyInterpreterState *interp;
732 PyThreadState *tstate, *save_tstate;
733 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 if (!initialized)
736 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 interp = PyInterpreterState_New();
739 if (interp == NULL)
740 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 tstate = PyThreadState_New(interp);
743 if (tstate == NULL) {
744 PyInterpreterState_Delete(interp);
745 return NULL;
746 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000753
Victor Stinner49d3f252010-10-17 01:24:53 +0000754 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 if (bimod != NULL) {
756 interp->builtins = PyModule_GetDict(bimod);
757 if (interp->builtins == NULL)
758 goto handle_error;
759 Py_INCREF(interp->builtins);
760 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400763 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000764
Victor Stinner49d3f252010-10-17 01:24:53 +0000765 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 if (bimod != NULL && sysmod != NULL) {
767 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 interp->sysdict = PyModule_GetDict(sysmod);
770 if (interp->sysdict == NULL)
771 goto handle_error;
772 Py_INCREF(interp->sysdict);
773 PySys_SetPath(Py_GetPath());
774 PyDict_SetItemString(interp->sysdict, "modules",
775 interp->modules);
776 /* Set up a preliminary stderr printer until we have enough
777 infrastructure for the io module in place. */
778 pstderr = PyFile_NewStdPrinter(fileno(stderr));
779 if (pstderr == NULL)
780 Py_FatalError("Py_Initialize: can't set preliminary stderr");
781 PySys_SetObject("stderr", pstderr);
782 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000783 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200786
Brett Cannonfd074152012-04-14 14:10:13 -0400787 import_init(interp, sysmod);
788
Victor Stinner793b5312011-04-27 00:24:21 +0200789 if (initfsencoding(interp) < 0)
790 goto handle_error;
791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (initstdio() < 0)
793 Py_FatalError(
794 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000795 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (!Py_NoSiteFlag)
797 initsite();
798 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 if (!PyErr_Occurred())
801 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000802
Thomas Wouters89f507f2006-12-13 04:49:30 +0000803handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000805
Victor Stinnerc40a3502011-04-27 00:20:27 +0200806 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 PyThreadState_Clear(tstate);
808 PyThreadState_Swap(save_tstate);
809 PyThreadState_Delete(tstate);
810 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000813}
814
815/* Delete an interpreter and its last thread. This requires that the
816 given thread state is current, that the thread has no remaining
817 frames, and that it is its interpreter's only remaining thread.
818 It is a fatal error to violate these constraints.
819
820 (Py_Finalize() doesn't have these constraints -- it zaps
821 everything, regardless.)
822
823 Locking: as above.
824
825*/
826
827void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000828Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 if (tstate != PyThreadState_GET())
833 Py_FatalError("Py_EndInterpreter: thread is not current");
834 if (tstate->frame != NULL)
835 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200836
837 wait_for_thread_shutdown();
838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 if (tstate != interp->tstate_head || tstate->next != NULL)
840 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 PyImport_Cleanup();
843 PyInterpreterState_Clear(interp);
844 PyThreadState_Swap(NULL);
845 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000846}
847
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200848#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000849static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200850#else
851static wchar_t *progname = L"python3";
852#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000853
854void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000855Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 if (pn && *pn)
858 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000859}
860
Martin v. Löwis790465f2008-04-05 20:41:37 +0000861wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000862Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000865}
866
Martin v. Löwis790465f2008-04-05 20:41:37 +0000867static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200868static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000869
870void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000871Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000874}
875
Martin v. Löwis790465f2008-04-05 20:41:37 +0000876wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000877Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 wchar_t *home = default_home;
880 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
881 char* chome = Py_GETENV("PYTHONHOME");
882 if (chome) {
883 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
884 if (r != (size_t)-1 && r <= PATH_MAX)
885 home = env_home;
886 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 }
889 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000890}
891
Guido van Rossum6135a871995-01-09 17:53:26 +0000892/* Create __main__ module */
893
894static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000895initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000896{
Brett Cannon13853a62013-05-04 17:37:09 -0400897 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 m = PyImport_AddModule("__main__");
899 if (m == NULL)
900 Py_FatalError("can't create __main__ module");
901 d = PyModule_GetDict(m);
902 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
903 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000904 if (bimod == NULL) {
905 Py_FatalError("Failed to retrieve builtins module");
906 }
907 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
908 Py_FatalError("Failed to initialize __main__.__builtins__");
909 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 Py_DECREF(bimod);
911 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000912 /* Main is a little special - imp.is_builtin("__main__") will return
913 * False, but BuiltinImporter is still the most appropriate initial
914 * setting for its __loader__ attribute. A more suitable value will
915 * be set if __main__ gets further initialized later in the startup
916 * process.
917 */
Brett Cannon13853a62013-05-04 17:37:09 -0400918 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400919 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000920 PyObject *loader = PyObject_GetAttrString(interp->importlib,
921 "BuiltinImporter");
922 if (loader == NULL) {
923 Py_FatalError("Failed to retrieve BuiltinImporter");
924 }
925 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
926 Py_FatalError("Failed to initialize __main__.__loader__");
927 }
928 Py_DECREF(loader);
929 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000930}
931
Victor Stinner793b5312011-04-27 00:24:21 +0200932static int
933initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000934{
935 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000936
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200937 if (Py_FileSystemDefaultEncoding == NULL)
938 {
939 Py_FileSystemDefaultEncoding = get_locale_encoding();
940 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000941 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000942
Victor Stinnere4743092010-10-19 00:05:51 +0000943 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200944 interp->fscodec_initialized = 1;
945 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000946 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000947
948 /* the encoding is mbcs, utf-8 or ascii */
949 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
950 if (!codec) {
951 /* Such error can only occurs in critical situations: no more
952 * memory, import a module of the standard library failed,
953 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200954 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000955 }
Victor Stinner793b5312011-04-27 00:24:21 +0200956 Py_DECREF(codec);
957 interp->fscodec_initialized = 1;
958 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000959}
960
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000961/* Import the site module (not into __main__ though) */
962
963static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000964initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PyObject *m;
967 m = PyImport_ImportModule("site");
968 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200969 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 PyErr_Print();
971 Py_Finalize();
972 exit(1);
973 }
974 else {
975 Py_DECREF(m);
976 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000977}
978
Antoine Pitrou05608432009-01-09 18:53:14 +0000979static PyObject*
980create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 int fd, int write_mode, char* name,
982 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000983{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
985 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000986 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 PyObject *line_buffering;
988 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200989 _Py_IDENTIFIER(open);
990 _Py_IDENTIFIER(isatty);
991 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200992 _Py_IDENTIFIER(name);
993 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 /* stdin is always opened in buffered mode, first because it shouldn't
996 make a difference in common use cases, second because TextIOWrapper
997 depends on the presence of a read1() method which only exists on
998 buffered streams.
999 */
1000 if (Py_UnbufferedStdioFlag && write_mode)
1001 buffering = 0;
1002 else
1003 buffering = -1;
1004 if (write_mode)
1005 mode = "wb";
1006 else
1007 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001008 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1009 fd, mode, buffering,
1010 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 if (buf == NULL)
1012 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001015 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001016 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (raw == NULL)
1018 goto error;
1019 }
1020 else {
1021 raw = buf;
1022 Py_INCREF(raw);
1023 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001026 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001028 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 if (res == NULL)
1030 goto error;
1031 isatty = PyObject_IsTrue(res);
1032 Py_DECREF(res);
1033 if (isatty == -1)
1034 goto error;
1035 if (isatty || Py_UnbufferedStdioFlag)
1036 line_buffering = Py_True;
1037 else
1038 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 Py_CLEAR(raw);
1041 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001042
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001043#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001044 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1045 newlines to "\n".
1046 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1047 newline = NULL;
1048#else
1049 /* sys.stdin: split lines at "\n".
1050 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1051 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001052#endif
1053
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001054 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1055 buf, encoding, errors,
1056 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 Py_CLEAR(buf);
1058 if (stream == NULL)
1059 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 if (write_mode)
1062 mode = "w";
1063 else
1064 mode = "r";
1065 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001066 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 goto error;
1068 Py_CLEAR(text);
1069 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001070
1071error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 Py_XDECREF(buf);
1073 Py_XDECREF(stream);
1074 Py_XDECREF(text);
1075 Py_XDECREF(raw);
1076 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001077}
1078
Antoine Pitrou11942a52011-11-28 19:08:36 +01001079static int
1080is_valid_fd(int fd)
1081{
1082 int dummy_fd;
1083 if (fd < 0 || !_PyVerify_fd(fd))
1084 return 0;
1085 dummy_fd = dup(fd);
1086 if (dummy_fd < 0)
1087 return 0;
1088 close(dummy_fd);
1089 return 1;
1090}
1091
Georg Brandl1a3284e2007-12-02 09:40:06 +00001092/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001093static int
1094initstdio(void)
1095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 PyObject *iomod = NULL, *wrapper;
1097 PyObject *bimod = NULL;
1098 PyObject *m;
1099 PyObject *std = NULL;
1100 int status = 0, fd;
1101 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001102 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 /* Hack to avoid a nasty recursion issue when Python is invoked
1105 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1106 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1107 goto error;
1108 }
1109 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1112 goto error;
1113 }
1114 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (!(bimod = PyImport_ImportModule("builtins"))) {
1117 goto error;
1118 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 if (!(iomod = PyImport_ImportModule("io"))) {
1121 goto error;
1122 }
1123 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1124 goto error;
1125 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 /* Set builtins.open */
1128 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001129 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 goto error;
1131 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001132 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001133
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001134 encoding = _Py_StandardStreamEncoding;
1135 errors = _Py_StandardStreamErrors;
1136 if (!encoding || !errors) {
1137 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1138 if (pythonioencoding) {
1139 char *err;
1140 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1141 if (pythonioencoding == NULL) {
1142 PyErr_NoMemory();
1143 goto error;
1144 }
1145 err = strchr(pythonioencoding, ':');
1146 if (err) {
1147 *err = '\0';
1148 err++;
1149 if (*err && !errors) {
1150 errors = err;
1151 }
1152 }
1153 if (*pythonioencoding && !encoding) {
1154 encoding = pythonioencoding;
1155 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001156 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 /* Set sys.stdin */
1160 fd = fileno(stdin);
1161 /* Under some conditions stdin, stdout and stderr may not be connected
1162 * and fileno() may point to an invalid file descriptor. For example
1163 * GUI apps don't have valid standard streams by default.
1164 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001165 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 std = Py_None;
1167 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 }
1169 else {
1170 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1171 if (std == NULL)
1172 goto error;
1173 } /* if (fd < 0) */
1174 PySys_SetObject("__stdin__", std);
1175 PySys_SetObject("stdin", std);
1176 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 /* Set sys.stdout */
1179 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001180 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 std = Py_None;
1182 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 }
1184 else {
1185 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1186 if (std == NULL)
1187 goto error;
1188 } /* if (fd < 0) */
1189 PySys_SetObject("__stdout__", std);
1190 PySys_SetObject("stdout", std);
1191 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001192
Guido van Rossum98297ee2007-11-06 21:34:58 +00001193#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 /* Set sys.stderr, replaces the preliminary stderr */
1195 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001196 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 std = Py_None;
1198 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 }
1200 else {
1201 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1202 if (std == NULL)
1203 goto error;
1204 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 /* Same as hack above, pre-import stderr's codec to avoid recursion
1207 when import.c tries to write to stderr in verbose mode. */
1208 encoding_attr = PyObject_GetAttrString(std, "encoding");
1209 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001210 const char * std_encoding;
1211 std_encoding = _PyUnicode_AsString(encoding_attr);
1212 if (std_encoding != NULL) {
1213 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001214 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001216 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 }
1218 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001219
Victor Stinnerba308832013-07-22 23:55:19 +02001220 if (PySys_SetObject("__stderr__", std) < 0) {
1221 Py_DECREF(std);
1222 goto error;
1223 }
1224 if (PySys_SetObject("stderr", std) < 0) {
1225 Py_DECREF(std);
1226 goto error;
1227 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001229#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001232 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 status = -1;
1234 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001235
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001236 /* We won't need them anymore. */
1237 if (_Py_StandardStreamEncoding) {
1238 PyMem_RawFree(_Py_StandardStreamEncoding);
1239 _Py_StandardStreamEncoding = NULL;
1240 }
1241 if (_Py_StandardStreamErrors) {
1242 PyMem_RawFree(_Py_StandardStreamErrors);
1243 _Py_StandardStreamErrors = NULL;
1244 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001245 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 Py_XDECREF(bimod);
1247 Py_XDECREF(iomod);
1248 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001249}
1250
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001251/* Parse input from a file and execute it */
1252
1253int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001254PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (filename == NULL)
1258 filename = "???";
1259 if (Py_FdIsInteractive(fp, filename)) {
1260 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1261 if (closeit)
1262 fclose(fp);
1263 return err;
1264 }
1265 else
1266 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001267}
1268
1269int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001270PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyObject *v;
1273 int ret;
1274 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 if (flags == NULL) {
1277 flags = &local_flags;
1278 local_flags.cf_flags = 0;
1279 }
1280 v = PySys_GetObject("ps1");
1281 if (v == NULL) {
1282 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1283 Py_XDECREF(v);
1284 }
1285 v = PySys_GetObject("ps2");
1286 if (v == NULL) {
1287 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1288 Py_XDECREF(v);
1289 }
1290 for (;;) {
1291 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1292 PRINT_TOTAL_REFS();
1293 if (ret == E_EOF)
1294 return 0;
1295 /*
1296 if (ret == E_NOMEM)
1297 return -1;
1298 */
1299 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001300}
1301
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001302/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001303static int PARSER_FLAGS(PyCompilerFlags *flags)
1304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 int parser_flags = 0;
1306 if (!flags)
1307 return 0;
1308 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1309 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1310 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1311 parser_flags |= PyPARSE_IGNORE_COOKIE;
1312 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1313 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1314 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001315}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001316
Thomas Wouters89f507f2006-12-13 04:49:30 +00001317#if 0
1318/* Keep an example of flags with future keyword support. */
1319#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1321 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1322 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1323 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001324#endif
1325
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001326int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001327PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 PyObject *m, *d, *v, *w, *oenc = NULL;
1330 mod_ty mod;
1331 PyArena *arena;
1332 char *ps1 = "", *ps2 = "", *enc = NULL;
1333 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001334 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001337 /* Fetch encoding from sys.stdin if possible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 v = PySys_GetObject("stdin");
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001339 if (v && v != Py_None) {
1340 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1341 if (oenc)
1342 enc = _PyUnicode_AsString(oenc);
1343 if (!enc)
1344 PyErr_Clear();
1345 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 }
1347 v = PySys_GetObject("ps1");
1348 if (v != NULL) {
1349 v = PyObject_Str(v);
1350 if (v == NULL)
1351 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001352 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001354 if (ps1 == NULL) {
1355 PyErr_Clear();
1356 ps1 = "";
1357 }
1358 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 }
1360 w = PySys_GetObject("ps2");
1361 if (w != NULL) {
1362 w = PyObject_Str(w);
1363 if (w == NULL)
1364 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001365 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001367 if (ps2 == NULL) {
1368 PyErr_Clear();
1369 ps2 = "";
1370 }
1371 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 }
1373 arena = PyArena_New();
1374 if (arena == NULL) {
1375 Py_XDECREF(v);
1376 Py_XDECREF(w);
1377 Py_XDECREF(oenc);
1378 return -1;
1379 }
1380 mod = PyParser_ASTFromFile(fp, filename, enc,
1381 Py_single_input, ps1, ps2,
1382 flags, &errcode, arena);
1383 Py_XDECREF(v);
1384 Py_XDECREF(w);
1385 Py_XDECREF(oenc);
1386 if (mod == NULL) {
1387 PyArena_Free(arena);
1388 if (errcode == E_EOF) {
1389 PyErr_Clear();
1390 return E_EOF;
1391 }
1392 PyErr_Print();
1393 return -1;
1394 }
1395 m = PyImport_AddModule("__main__");
1396 if (m == NULL) {
1397 PyArena_Free(arena);
1398 return -1;
1399 }
1400 d = PyModule_GetDict(m);
1401 v = run_mod(mod, filename, d, d, flags, arena);
1402 PyArena_Free(arena);
1403 flush_io();
1404 if (v == NULL) {
1405 PyErr_Print();
1406 return -1;
1407 }
1408 Py_DECREF(v);
1409 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001410}
1411
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001412/* Check whether a file maybe a pyc file: Look at the extension,
1413 the file type, and, if we may close it, at the first few bytes. */
1414
1415static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001416maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1419 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 /* Only look into the file if we are allowed to close it, since
1422 it then should also be seekable. */
1423 if (closeit) {
1424 /* Read only two bytes of the magic. If the file was opened in
1425 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1426 be read as they are on disk. */
1427 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1428 unsigned char buf[2];
1429 /* Mess: In case of -x, the stream is NOT at its start now,
1430 and ungetc() was used to push back the first newline,
1431 which makes the current stream position formally undefined,
1432 and a x-platform nightmare.
1433 Unfortunately, we have no direct way to know whether -x
1434 was specified. So we use a terrible hack: if the current
1435 stream position is not 0, we assume -x was specified, and
1436 give up. Bug 132850 on SourceForge spells out the
1437 hopelessness of trying anything else (fseek and ftell
1438 don't work predictably x-platform for text-mode files).
1439 */
1440 int ispyc = 0;
1441 if (ftell(fp) == 0) {
1442 if (fread(buf, 1, 2, fp) == 2 &&
1443 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1444 ispyc = 1;
1445 rewind(fp);
1446 }
1447 return ispyc;
1448 }
1449 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001450}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001451
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001452static int
1453set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001454{
1455 PyInterpreterState *interp;
1456 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001457 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001458 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001459
1460 filename_obj = PyUnicode_DecodeFSDefault(filename);
1461 if (filename_obj == NULL)
1462 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001463 /* Get current thread state and interpreter pointer */
1464 tstate = PyThreadState_GET();
1465 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001466 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1467 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001468 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001469 return -1;
1470 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001471 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001472 Py_DECREF(loader_type);
1473 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001474 return -1;
1475 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001476 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1477 result = -1;
1478 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001479 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001480 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001481}
1482
1483int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001484PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 PyObject *m, *d, *v;
1488 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001489 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001490 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 m = PyImport_AddModule("__main__");
1493 if (m == NULL)
1494 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001495 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 d = PyModule_GetDict(m);
1497 if (PyDict_GetItemString(d, "__file__") == NULL) {
1498 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001499 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001501 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001502 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1503 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001504 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001506 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1507 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001508 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001509 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 set_file_name = 1;
1511 Py_DECREF(f);
1512 }
1513 len = strlen(filename);
1514 ext = filename + len - (len > 4 ? 4 : 0);
1515 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001516 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 /* Try to run a pyc file. First, re-open in binary */
1518 if (closeit)
1519 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001520 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 goto done;
1523 }
1524 /* Turn on optimization if a .pyo file is given */
1525 if (strcmp(ext, ".pyo") == 0)
1526 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001527
1528 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1529 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1530 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001531 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001532 goto done;
1533 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001534 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1535 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001537 /* When running from stdin, leave __main__.__loader__ alone */
1538 if (strcmp(filename, "<stdin>") != 0 &&
1539 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1540 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1541 ret = -1;
1542 goto done;
1543 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1545 closeit, flags);
1546 }
1547 flush_io();
1548 if (v == NULL) {
1549 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 goto done;
1551 }
1552 Py_DECREF(v);
1553 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001554 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1556 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001557 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001559}
1560
1561int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001562PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 PyObject *m, *d, *v;
1565 m = PyImport_AddModule("__main__");
1566 if (m == NULL)
1567 return -1;
1568 d = PyModule_GetDict(m);
1569 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1570 if (v == NULL) {
1571 PyErr_Print();
1572 return -1;
1573 }
1574 Py_DECREF(v);
1575 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001576}
1577
Barry Warsaw035574d1997-08-29 22:07:17 +00001578static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001579parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 long hold;
1583 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001584 _Py_IDENTIFIER(msg);
1585 _Py_IDENTIFIER(filename);
1586 _Py_IDENTIFIER(lineno);
1587 _Py_IDENTIFIER(offset);
1588 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001589
Benjamin Peterson80d50422012-04-03 00:30:38 -04001590 *message = NULL;
1591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001593 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001594 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001596
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001597 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001598 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001600 if (v == Py_None) {
1601 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001603 }
1604 else {
1605 *filename = _PyUnicode_AsString(v);
1606 Py_DECREF(v);
1607 if (!*filename)
1608 goto finally;
1609 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001610
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001611 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001612 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 goto finally;
1614 hold = PyLong_AsLong(v);
1615 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 if (hold < 0 && PyErr_Occurred())
1617 goto finally;
1618 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001619
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001620 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001621 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 goto finally;
1623 if (v == Py_None) {
1624 *offset = -1;
1625 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 } else {
1627 hold = PyLong_AsLong(v);
1628 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 if (hold < 0 && PyErr_Occurred())
1630 goto finally;
1631 *offset = (int)hold;
1632 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001633
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001634 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001635 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001637 if (v == Py_None) {
1638 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001640 }
1641 else {
1642 *text = _PyUnicode_AsString(v);
1643 Py_DECREF(v);
1644 if (!*text)
1645 goto finally;
1646 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001648
1649finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001650 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001652}
1653
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001654void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001655PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001658}
1659
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001660static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001661print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 char *nl;
1664 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001665 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1666 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 for (;;) {
1668 nl = strchr(text, '\n');
1669 if (nl == NULL || nl-text >= offset)
1670 break;
1671 offset -= (int)(nl+1-text);
1672 text = nl+1;
1673 }
1674 while (*text == ' ' || *text == '\t') {
1675 text++;
1676 offset--;
1677 }
1678 }
1679 PyFile_WriteString(" ", f);
1680 PyFile_WriteString(text, f);
1681 if (*text == '\0' || text[strlen(text)-1] != '\n')
1682 PyFile_WriteString("\n", f);
1683 if (offset == -1)
1684 return;
1685 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001686 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001689}
1690
Guido van Rossum66e8e862001-03-23 17:54:43 +00001691static void
1692handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 PyObject *exception, *value, *tb;
1695 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001696
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 if (Py_InspectFlag)
1698 /* Don't exit if -i flag was given. This flag is set to 0
1699 * when entering interactive mode for inspecting. */
1700 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 PyErr_Fetch(&exception, &value, &tb);
1703 fflush(stdout);
1704 if (value == NULL || value == Py_None)
1705 goto done;
1706 if (PyExceptionInstance_Check(value)) {
1707 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001708 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001709 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 if (code) {
1711 Py_DECREF(value);
1712 value = code;
1713 if (value == Py_None)
1714 goto done;
1715 }
1716 /* If we failed to dig out the 'code' attribute,
1717 just let the else clause below print the error. */
1718 }
1719 if (PyLong_Check(value))
1720 exitcode = (int)PyLong_AsLong(value);
1721 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001722 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001723 if (sys_stderr != NULL && sys_stderr != Py_None) {
1724 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1725 } else {
1726 PyObject_Print(value, stderr, Py_PRINT_RAW);
1727 fflush(stderr);
1728 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 PySys_WriteStderr("\n");
1730 exitcode = 1;
1731 }
Tim Peterscf615b52003-04-19 18:47:02 +00001732 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 /* Restore and clear the exception info, in order to properly decref
1734 * the exception, value, and traceback. If we just exit instead,
1735 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1736 * some finalizers from running.
1737 */
1738 PyErr_Restore(exception, value, tb);
1739 PyErr_Clear();
1740 Py_Exit(exitcode);
1741 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001742}
1743
1744void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001745PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1750 handle_system_exit();
1751 }
1752 PyErr_Fetch(&exception, &v, &tb);
1753 if (exception == NULL)
1754 return;
1755 PyErr_NormalizeException(&exception, &v, &tb);
1756 if (tb == NULL) {
1757 tb = Py_None;
1758 Py_INCREF(tb);
1759 }
1760 PyException_SetTraceback(v, tb);
1761 if (exception == NULL)
1762 return;
1763 /* Now we know v != NULL too */
1764 if (set_sys_last_vars) {
1765 PySys_SetObject("last_type", exception);
1766 PySys_SetObject("last_value", v);
1767 PySys_SetObject("last_traceback", tb);
1768 }
1769 hook = PySys_GetObject("excepthook");
1770 if (hook) {
1771 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1772 PyObject *result = PyEval_CallObject(hook, args);
1773 if (result == NULL) {
1774 PyObject *exception2, *v2, *tb2;
1775 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1776 handle_system_exit();
1777 }
1778 PyErr_Fetch(&exception2, &v2, &tb2);
1779 PyErr_NormalizeException(&exception2, &v2, &tb2);
1780 /* It should not be possible for exception2 or v2
1781 to be NULL. However PyErr_Display() can't
1782 tolerate NULLs, so just be safe. */
1783 if (exception2 == NULL) {
1784 exception2 = Py_None;
1785 Py_INCREF(exception2);
1786 }
1787 if (v2 == NULL) {
1788 v2 = Py_None;
1789 Py_INCREF(v2);
1790 }
1791 fflush(stdout);
1792 PySys_WriteStderr("Error in sys.excepthook:\n");
1793 PyErr_Display(exception2, v2, tb2);
1794 PySys_WriteStderr("\nOriginal exception was:\n");
1795 PyErr_Display(exception, v, tb);
1796 Py_DECREF(exception2);
1797 Py_DECREF(v2);
1798 Py_XDECREF(tb2);
1799 }
1800 Py_XDECREF(result);
1801 Py_XDECREF(args);
1802 } else {
1803 PySys_WriteStderr("sys.excepthook is missing\n");
1804 PyErr_Display(exception, v, tb);
1805 }
1806 Py_XDECREF(exception);
1807 Py_XDECREF(v);
1808 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001809}
1810
Benjamin Petersone6528212008-07-15 15:32:09 +00001811static void
1812print_exception(PyObject *f, PyObject *value)
1813{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 int err = 0;
1815 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001816 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (!PyExceptionInstance_Check(value)) {
1819 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1820 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1821 PyFile_WriteString(" found\n", f);
1822 return;
1823 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 Py_INCREF(value);
1826 fflush(stdout);
1827 type = (PyObject *) Py_TYPE(value);
1828 tb = PyException_GetTraceback(value);
1829 if (tb && tb != Py_None)
1830 err = PyTraceBack_Print(tb, f);
1831 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001832 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 {
1834 PyObject *message;
1835 const char *filename, *text;
1836 int lineno, offset;
1837 if (!parse_syntax_error(value, &message, &filename,
1838 &lineno, &offset, &text))
1839 PyErr_Clear();
1840 else {
1841 char buf[10];
1842 PyFile_WriteString(" File \"", f);
1843 if (filename == NULL)
1844 PyFile_WriteString("<string>", f);
1845 else
1846 PyFile_WriteString(filename, f);
1847 PyFile_WriteString("\", line ", f);
1848 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1849 PyFile_WriteString(buf, f);
1850 PyFile_WriteString("\n", f);
1851 if (text != NULL)
1852 print_error_text(f, offset, text);
1853 Py_DECREF(value);
1854 value = message;
1855 /* Can't be bothered to check all those
1856 PyFile_WriteString() calls */
1857 if (PyErr_Occurred())
1858 err = -1;
1859 }
1860 }
1861 if (err) {
1862 /* Don't do anything else */
1863 }
1864 else {
1865 PyObject* moduleName;
1866 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001867 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 assert(PyExceptionClass_Check(type));
1869 className = PyExceptionClass_Name(type);
1870 if (className != NULL) {
1871 char *dot = strrchr(className, '.');
1872 if (dot != NULL)
1873 className = dot+1;
1874 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001875
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001876 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1878 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001879 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 err = PyFile_WriteString("<unknown>", f);
1881 }
1882 else {
1883 char* modstr = _PyUnicode_AsString(moduleName);
1884 if (modstr && strcmp(modstr, "builtins"))
1885 {
1886 err = PyFile_WriteString(modstr, f);
1887 err += PyFile_WriteString(".", f);
1888 }
1889 Py_DECREF(moduleName);
1890 }
1891 if (err == 0) {
1892 if (className == NULL)
1893 err = PyFile_WriteString("<unknown>", f);
1894 else
1895 err = PyFile_WriteString(className, f);
1896 }
1897 }
1898 if (err == 0 && (value != Py_None)) {
1899 PyObject *s = PyObject_Str(value);
1900 /* only print colon if the str() of the
1901 object is not the empty string
1902 */
1903 if (s == NULL)
1904 err = -1;
1905 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001906 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001907 err = PyFile_WriteString(": ", f);
1908 if (err == 0)
1909 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1910 Py_XDECREF(s);
1911 }
1912 /* try to write a newline in any case */
1913 err += PyFile_WriteString("\n", f);
1914 Py_XDECREF(tb);
1915 Py_DECREF(value);
1916 /* If an error happened here, don't show it.
1917 XXX This is wrong, but too many callers rely on this behavior. */
1918 if (err != 0)
1919 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001920}
1921
1922static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 "\nThe above exception was the direct cause "
1924 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001925
1926static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 "\nDuring handling of the above exception, "
1928 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001929
1930static void
1931print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 int err = 0, res;
1934 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 if (seen != NULL) {
1937 /* Exception chaining */
1938 if (PySet_Add(seen, value) == -1)
1939 PyErr_Clear();
1940 else if (PyExceptionInstance_Check(value)) {
1941 cause = PyException_GetCause(value);
1942 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001943 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 res = PySet_Contains(seen, cause);
1945 if (res == -1)
1946 PyErr_Clear();
1947 if (res == 0) {
1948 print_exception_recursive(
1949 f, cause, seen);
1950 err |= PyFile_WriteString(
1951 cause_message, f);
1952 }
1953 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001954 else if (context &&
1955 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 res = PySet_Contains(seen, context);
1957 if (res == -1)
1958 PyErr_Clear();
1959 if (res == 0) {
1960 print_exception_recursive(
1961 f, context, seen);
1962 err |= PyFile_WriteString(
1963 context_message, f);
1964 }
1965 }
1966 Py_XDECREF(context);
1967 Py_XDECREF(cause);
1968 }
1969 }
1970 print_exception(f, value);
1971 if (err != 0)
1972 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001973}
1974
Thomas Wouters477c8d52006-05-27 19:21:47 +00001975void
1976PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 PyObject *seen;
1979 PyObject *f = PySys_GetObject("stderr");
Antoine Pitrou24201d42013-10-13 21:53:13 +02001980 if (PyExceptionInstance_Check(value)
1981 && tb != NULL && PyTraceBack_Check(tb)) {
1982 /* Put the traceback on the exception, otherwise it won't get
1983 displayed. See issue #18776. */
1984 PyObject *cur_tb = PyException_GetTraceback(value);
1985 if (cur_tb == NULL)
1986 PyException_SetTraceback(value, tb);
1987 else
1988 Py_DECREF(cur_tb);
1989 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 if (f == Py_None) {
1991 /* pass */
1992 }
1993 else if (f == NULL) {
1994 _PyObject_Dump(value);
1995 fprintf(stderr, "lost sys.stderr\n");
1996 }
1997 else {
1998 /* We choose to ignore seen being possibly NULL, and report
1999 at least the main exception (it could be a MemoryError).
2000 */
2001 seen = PySet_New(NULL);
2002 if (seen == NULL)
2003 PyErr_Clear();
2004 print_exception_recursive(f, value, seen);
2005 Py_XDECREF(seen);
2006 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002007}
2008
Guido van Rossum82598051997-03-05 00:20:32 +00002009PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002010PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 PyObject *ret = NULL;
2014 mod_ty mod;
2015 PyArena *arena = PyArena_New();
2016 if (arena == NULL)
2017 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
2020 if (mod != NULL)
2021 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
2022 PyArena_Free(arena);
2023 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002024}
2025
2026PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002027PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 PyObject *ret;
2031 mod_ty mod;
2032 PyArena *arena = PyArena_New();
2033 if (arena == NULL)
2034 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
2037 flags, NULL, arena);
2038 if (closeit)
2039 fclose(fp);
2040 if (mod == NULL) {
2041 PyArena_Free(arena);
2042 return NULL;
2043 }
2044 ret = run_mod(mod, filename, globals, locals, flags, arena);
2045 PyArena_Free(arena);
2046 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002047}
2048
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002049static void
2050flush_io(void)
2051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 PyObject *f, *r;
2053 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002054 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 /* Save the current exception */
2057 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 f = PySys_GetObject("stderr");
2060 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002061 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 if (r)
2063 Py_DECREF(r);
2064 else
2065 PyErr_Clear();
2066 }
2067 f = PySys_GetObject("stdout");
2068 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002069 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (r)
2071 Py_DECREF(r);
2072 else
2073 PyErr_Clear();
2074 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002077}
2078
Guido van Rossum82598051997-03-05 00:20:32 +00002079static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002080run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 PyCodeObject *co;
2084 PyObject *v;
2085 co = PyAST_Compile(mod, filename, flags, arena);
2086 if (co == NULL)
2087 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002088 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 Py_DECREF(co);
2090 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002091}
2092
Guido van Rossum82598051997-03-05 00:20:32 +00002093static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002094run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 PyCodeObject *co;
2098 PyObject *v;
2099 long magic;
2100 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 magic = PyMarshal_ReadLongFromFile(fp);
2103 if (magic != PyImport_GetMagicNumber()) {
2104 PyErr_SetString(PyExc_RuntimeError,
2105 "Bad magic number in .pyc file");
2106 return NULL;
2107 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002108 /* Skip mtime and size */
2109 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 (void) PyMarshal_ReadLongFromFile(fp);
2111 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (v == NULL || !PyCode_Check(v)) {
2113 Py_XDECREF(v);
2114 PyErr_SetString(PyExc_RuntimeError,
2115 "Bad code object in .pyc file");
2116 return NULL;
2117 }
2118 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002119 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 if (v && flags)
2121 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2122 Py_DECREF(co);
2123 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002124}
2125
Guido van Rossum82598051997-03-05 00:20:32 +00002126PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002127Py_CompileStringObject(const char *str, PyObject *filename, int start,
2128 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyCodeObject *co;
2131 mod_ty mod;
2132 PyArena *arena = PyArena_New();
2133 if (arena == NULL)
2134 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002135
Victor Stinner14e461d2013-08-26 22:28:21 +02002136 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (mod == NULL) {
2138 PyArena_Free(arena);
2139 return NULL;
2140 }
2141 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2142 PyObject *result = PyAST_mod2obj(mod);
2143 PyArena_Free(arena);
2144 return result;
2145 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002146 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 PyArena_Free(arena);
2148 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002149}
2150
Victor Stinner14e461d2013-08-26 22:28:21 +02002151PyObject *
2152Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2153 PyCompilerFlags *flags, int optimize)
2154{
2155 PyObject *filename, *co;
2156 filename = PyUnicode_DecodeFSDefault(filename_str);
2157 if (filename == NULL)
2158 return NULL;
2159 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2160 Py_DECREF(filename);
2161 return co;
2162}
2163
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002164/* For use in Py_LIMITED_API */
2165#undef Py_CompileString
2166PyObject *
2167PyCompileString(const char *str, const char *filename, int start)
2168{
2169 return Py_CompileStringFlags(str, filename, start, NULL);
2170}
2171
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002172struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002173Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 struct symtable *st;
2176 mod_ty mod;
2177 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002178 PyArena *arena;
2179
2180 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 if (arena == NULL)
2182 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002185 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (mod == NULL) {
2187 PyArena_Free(arena);
2188 return NULL;
2189 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002190 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 PyArena_Free(arena);
2192 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002193}
2194
Victor Stinner14e461d2013-08-26 22:28:21 +02002195struct symtable *
2196Py_SymtableString(const char *str, const char *filename_str, int start)
2197{
2198 PyObject *filename;
2199 struct symtable *st;
2200
2201 filename = PyUnicode_DecodeFSDefault(filename_str);
2202 if (filename == NULL)
2203 return NULL;
2204 st = Py_SymtableStringObject(str, filename, start);
2205 Py_DECREF(filename);
2206 return st;
2207}
2208
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209/* Preferred access to parser is through AST. */
2210mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002211PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2212 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 mod_ty mod;
2215 PyCompilerFlags localflags;
2216 perrdetail err;
2217 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002218
Victor Stinner14e461d2013-08-26 22:28:21 +02002219 node *n = PyParser_ParseStringObject(s, filename,
2220 &_PyParser_Grammar, start, &err,
2221 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 if (flags == NULL) {
2223 localflags.cf_flags = 0;
2224 flags = &localflags;
2225 }
2226 if (n) {
2227 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002228 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 }
2231 else {
2232 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002233 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002235 err_free(&err);
2236 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002237}
2238
2239mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002240PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2241 PyCompilerFlags *flags, PyArena *arena)
2242{
2243 PyObject *filename;
2244 mod_ty mod;
2245 filename = PyUnicode_DecodeFSDefault(filename_str);
2246 if (filename == NULL)
2247 return NULL;
2248 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2249 Py_DECREF(filename);
2250 return mod;
2251}
2252
2253mod_ty
2254PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2255 int start, char *ps1,
2256 char *ps2, PyCompilerFlags *flags, int *errcode,
2257 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 mod_ty mod;
2260 PyCompilerFlags localflags;
2261 perrdetail err;
2262 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002263
Victor Stinner14e461d2013-08-26 22:28:21 +02002264 node *n = PyParser_ParseFileObject(fp, filename, enc,
2265 &_PyParser_Grammar,
2266 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 if (flags == NULL) {
2268 localflags.cf_flags = 0;
2269 flags = &localflags;
2270 }
2271 if (n) {
2272 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002273 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002275 }
2276 else {
2277 err_input(&err);
2278 if (errcode)
2279 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002280 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002282 err_free(&err);
2283 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284}
2285
Victor Stinner14e461d2013-08-26 22:28:21 +02002286mod_ty
2287PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2288 int start, char *ps1,
2289 char *ps2, PyCompilerFlags *flags, int *errcode,
2290 PyArena *arena)
2291{
2292 mod_ty mod;
2293 PyObject *filename;
2294 filename = PyUnicode_DecodeFSDefault(filename_str);
2295 if (filename == NULL)
2296 return NULL;
2297 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2298 flags, errcode, arena);
2299 Py_DECREF(filename);
2300 return mod;
2301}
2302
Guido van Rossuma110aa61994-08-29 12:50:44 +00002303/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002304
Guido van Rossuma110aa61994-08-29 12:50:44 +00002305node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002306PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 perrdetail err;
2309 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2310 &_PyParser_Grammar,
2311 start, NULL, NULL, &err, flags);
2312 if (n == NULL)
2313 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002314 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002317}
2318
Guido van Rossuma110aa61994-08-29 12:50:44 +00002319/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002320
Guido van Rossuma110aa61994-08-29 12:50:44 +00002321node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002322PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 perrdetail err;
2325 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2326 start, &err, flags);
2327 if (n == NULL)
2328 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002329 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002331}
2332
2333node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002334PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 perrdetail err;
2338 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2339 &_PyParser_Grammar, start, &err, flags);
2340 if (n == NULL)
2341 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002342 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002344}
2345
2346node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002347PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002348{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002350}
2351
Guido van Rossum66ebd912003-04-17 16:02:26 +00002352/* May want to move a more generalized form of this to parsetok.c or
2353 even parser modules. */
2354
2355void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002356PyParser_ClearError(perrdetail *err)
2357{
2358 err_free(err);
2359}
2360
2361void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002362PyParser_SetError(perrdetail *err)
2363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002365}
2366
Victor Stinner7f2fee32011-04-05 00:39:01 +02002367static void
2368err_free(perrdetail *err)
2369{
2370 Py_CLEAR(err->filename);
2371}
2372
Guido van Rossuma110aa61994-08-29 12:50:44 +00002373/* Set the error appropriate to the given input error code (see errcode.h) */
2374
2375static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002376err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 PyObject *v, *w, *errtype, *errtext;
2379 PyObject *msg_obj = NULL;
2380 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 errtype = PyExc_SyntaxError;
2383 switch (err->error) {
2384 case E_ERROR:
2385 return;
2386 case E_SYNTAX:
2387 errtype = PyExc_IndentationError;
2388 if (err->expected == INDENT)
2389 msg = "expected an indented block";
2390 else if (err->token == INDENT)
2391 msg = "unexpected indent";
2392 else if (err->token == DEDENT)
2393 msg = "unexpected unindent";
2394 else {
2395 errtype = PyExc_SyntaxError;
2396 msg = "invalid syntax";
2397 }
2398 break;
2399 case E_TOKEN:
2400 msg = "invalid token";
2401 break;
2402 case E_EOFS:
2403 msg = "EOF while scanning triple-quoted string literal";
2404 break;
2405 case E_EOLS:
2406 msg = "EOL while scanning string literal";
2407 break;
2408 case E_INTR:
2409 if (!PyErr_Occurred())
2410 PyErr_SetNone(PyExc_KeyboardInterrupt);
2411 goto cleanup;
2412 case E_NOMEM:
2413 PyErr_NoMemory();
2414 goto cleanup;
2415 case E_EOF:
2416 msg = "unexpected EOF while parsing";
2417 break;
2418 case E_TABSPACE:
2419 errtype = PyExc_TabError;
2420 msg = "inconsistent use of tabs and spaces in indentation";
2421 break;
2422 case E_OVERFLOW:
2423 msg = "expression too long";
2424 break;
2425 case E_DEDENT:
2426 errtype = PyExc_IndentationError;
2427 msg = "unindent does not match any outer indentation level";
2428 break;
2429 case E_TOODEEP:
2430 errtype = PyExc_IndentationError;
2431 msg = "too many levels of indentation";
2432 break;
2433 case E_DECODE: {
2434 PyObject *type, *value, *tb;
2435 PyErr_Fetch(&type, &value, &tb);
2436 msg = "unknown decode error";
2437 if (value != NULL)
2438 msg_obj = PyObject_Str(value);
2439 Py_XDECREF(type);
2440 Py_XDECREF(value);
2441 Py_XDECREF(tb);
2442 break;
2443 }
2444 case E_LINECONT:
2445 msg = "unexpected character after line continuation character";
2446 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 case E_IDENTIFIER:
2449 msg = "invalid character in identifier";
2450 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002451 case E_BADSINGLE:
2452 msg = "multiple statements found while compiling a single statement";
2453 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 default:
2455 fprintf(stderr, "error=%d\n", err->error);
2456 msg = "unknown parsing error";
2457 break;
2458 }
2459 /* err->text may not be UTF-8 in case of decoding errors.
2460 Explicitly convert to an object. */
2461 if (!err->text) {
2462 errtext = Py_None;
2463 Py_INCREF(Py_None);
2464 } else {
2465 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2466 "replace");
2467 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002468 v = Py_BuildValue("(OiiN)", err->filename,
2469 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 if (v != NULL) {
2471 if (msg_obj)
2472 w = Py_BuildValue("(OO)", msg_obj, v);
2473 else
2474 w = Py_BuildValue("(sO)", msg, v);
2475 } else
2476 w = NULL;
2477 Py_XDECREF(v);
2478 PyErr_SetObject(errtype, w);
2479 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002480cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 Py_XDECREF(msg_obj);
2482 if (err->text != NULL) {
2483 PyObject_FREE(err->text);
2484 err->text = NULL;
2485 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002486}
2487
2488/* Print fatal error message and abort */
2489
2490void
Tim Peters7c321a82002-07-09 02:57:01 +00002491Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002492{
Victor Stinner024e37a2011-03-31 01:31:06 +02002493 const int fd = fileno(stderr);
2494 PyThreadState *tstate;
2495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 fprintf(stderr, "Fatal Python error: %s\n", msg);
2497 fflush(stderr); /* it helps in Windows debug build */
2498 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002499 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002501 else {
2502 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2503 if (tstate != NULL) {
2504 fputc('\n', stderr);
2505 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002506 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002507 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002508 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002509 }
2510
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002511#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 {
2513 size_t len = strlen(msg);
2514 WCHAR* buffer;
2515 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 /* Convert the message to wchar_t. This uses a simple one-to-one
2518 conversion, assuming that the this error message actually uses ASCII
2519 only. If this ceases to be true, we will have to convert. */
2520 buffer = alloca( (len+1) * (sizeof *buffer));
2521 for( i=0; i<=len; ++i)
2522 buffer[i] = msg[i];
2523 OutputDebugStringW(L"Fatal Python error: ");
2524 OutputDebugStringW(buffer);
2525 OutputDebugStringW(L"\n");
2526 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002527#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002529#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002530#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002532}
2533
2534/* Clean up and exit */
2535
Guido van Rossuma110aa61994-08-29 12:50:44 +00002536#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002537#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002538#endif
2539
Collin Winter670e6922007-03-21 02:57:17 +00002540static void (*pyexitfunc)(void) = NULL;
2541/* For the atexit module. */
2542void _Py_PyAtExit(void (*func)(void))
2543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002545}
2546
2547static void
2548call_py_exitfuncs(void)
2549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 if (pyexitfunc == NULL)
2551 return;
Collin Winter670e6922007-03-21 02:57:17 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 (*pyexitfunc)();
2554 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002555}
2556
Antoine Pitrou011bd622009-10-20 21:52:47 +00002557/* Wait until threading._shutdown completes, provided
2558 the threading module was imported in the first place.
2559 The shutdown routine will wait until all non-daemon
2560 "threading" threads have completed. */
2561static void
2562wait_for_thread_shutdown(void)
2563{
2564#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002565 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 PyObject *result;
2567 PyThreadState *tstate = PyThreadState_GET();
2568 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2569 "threading");
2570 if (threading == NULL) {
2571 /* threading not imported */
2572 PyErr_Clear();
2573 return;
2574 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002575 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 if (result == NULL) {
2577 PyErr_WriteUnraisable(threading);
2578 }
2579 else {
2580 Py_DECREF(result);
2581 }
2582 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002583#endif
2584}
2585
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002586#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002587static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002588static int nexitfuncs = 0;
2589
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002590int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 if (nexitfuncs >= NEXITFUNCS)
2593 return -1;
2594 exitfuncs[nexitfuncs++] = func;
2595 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002596}
2597
Guido van Rossumcc283f51997-08-05 02:22:03 +00002598static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002599call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 while (nexitfuncs > 0)
2602 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 fflush(stdout);
2605 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002606}
2607
2608void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002609Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002614}
2615
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002616static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002617initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002618{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002619#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002621#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002622#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002624#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002625#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002627#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002629 if (PyErr_Occurred()) {
2630 Py_FatalError("Py_Initialize: can't import signal");
2631 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002632}
2633
Guido van Rossum7433b121997-02-14 19:45:36 +00002634
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002635/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2636 *
2637 * All of the code in this function must only use async-signal-safe functions,
2638 * listed at `man 7 signal` or
2639 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2640 */
2641void
2642_Py_RestoreSignals(void)
2643{
2644#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002646#endif
2647#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002649#endif
2650#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002652#endif
2653}
2654
2655
Guido van Rossum7433b121997-02-14 19:45:36 +00002656/*
2657 * The file descriptor fd is considered ``interactive'' if either
2658 * a) isatty(fd) is TRUE, or
2659 * b) the -i flag was given, and the filename associated with
2660 * the descriptor is NULL or "<stdin>" or "???".
2661 */
2662int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002663Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 if (isatty((int)fileno(fp)))
2666 return 1;
2667 if (!Py_InteractiveFlag)
2668 return 0;
2669 return (filename == NULL) ||
2670 (strcmp(filename, "<stdin>") == 0) ||
2671 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002672}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002673
2674
Tim Petersd08e3822003-04-17 15:24:21 +00002675#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002676#if defined(WIN32) && defined(_MSC_VER)
2677
2678/* Stack checking for Microsoft C */
2679
2680#include <malloc.h>
2681#include <excpt.h>
2682
Fred Drakee8de31c2000-08-31 05:38:39 +00002683/*
2684 * Return non-zero when we run out of memory on the stack; zero otherwise.
2685 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002686int
Fred Drake399739f2000-08-31 05:52:44 +00002687PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 __try {
2690 /* alloca throws a stack overflow exception if there's
2691 not enough space left on the stack */
2692 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2693 return 0;
2694 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2695 EXCEPTION_EXECUTE_HANDLER :
2696 EXCEPTION_CONTINUE_SEARCH) {
2697 int errcode = _resetstkoflw();
2698 if (errcode == 0)
2699 {
2700 Py_FatalError("Could not reset the stack!");
2701 }
2702 }
2703 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002704}
2705
2706#endif /* WIN32 && _MSC_VER */
2707
2708/* Alternate implementations can be added here... */
2709
2710#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002711
2712
2713/* Wrappers around sigaction() or signal(). */
2714
2715PyOS_sighandler_t
2716PyOS_getsig(int sig)
2717{
2718#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 struct sigaction context;
2720 if (sigaction(sig, NULL, &context) == -1)
2721 return SIG_ERR;
2722 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002723#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002725/* Special signal handling for the secure CRT in Visual Studio 2005 */
2726#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 switch (sig) {
2728 /* Only these signals are valid */
2729 case SIGINT:
2730 case SIGILL:
2731 case SIGFPE:
2732 case SIGSEGV:
2733 case SIGTERM:
2734 case SIGBREAK:
2735 case SIGABRT:
2736 break;
2737 /* Don't call signal() with other values or it will assert */
2738 default:
2739 return SIG_ERR;
2740 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002741#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 handler = signal(sig, SIG_IGN);
2743 if (handler != SIG_ERR)
2744 signal(sig, handler);
2745 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002746#endif
2747}
2748
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002749/*
2750 * All of the code in this function must only use async-signal-safe functions,
2751 * listed at `man 7 signal` or
2752 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2753 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002754PyOS_sighandler_t
2755PyOS_setsig(int sig, PyOS_sighandler_t handler)
2756{
2757#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 /* Some code in Modules/signalmodule.c depends on sigaction() being
2759 * used here if HAVE_SIGACTION is defined. Fix that if this code
2760 * changes to invalidate that assumption.
2761 */
2762 struct sigaction context, ocontext;
2763 context.sa_handler = handler;
2764 sigemptyset(&context.sa_mask);
2765 context.sa_flags = 0;
2766 if (sigaction(sig, &context, &ocontext) == -1)
2767 return SIG_ERR;
2768 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002769#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 PyOS_sighandler_t oldhandler;
2771 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002772#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002774#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002776#endif
2777}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002778
2779/* Deprecated C API functions still provided for binary compatiblity */
2780
2781#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002782PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002783PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786}
2787
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002788#undef PyParser_SimpleParseString
2789PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002790PyParser_SimpleParseString(const char *str, int start)
2791{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002793}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002794
2795#undef PyRun_AnyFile
2796PyAPI_FUNC(int)
2797PyRun_AnyFile(FILE *fp, const char *name)
2798{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002799 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002800}
2801
2802#undef PyRun_AnyFileEx
2803PyAPI_FUNC(int)
2804PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002806 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002807}
2808
2809#undef PyRun_AnyFileFlags
2810PyAPI_FUNC(int)
2811PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002814}
2815
2816#undef PyRun_File
2817PyAPI_FUNC(PyObject *)
2818PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002821}
2822
2823#undef PyRun_FileEx
2824PyAPI_FUNC(PyObject *)
2825PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002828}
2829
2830#undef PyRun_FileFlags
2831PyAPI_FUNC(PyObject *)
2832PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002836}
2837
2838#undef PyRun_SimpleFile
2839PyAPI_FUNC(int)
2840PyRun_SimpleFile(FILE *f, const char *p)
2841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002843}
2844
2845#undef PyRun_SimpleFileEx
2846PyAPI_FUNC(int)
2847PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002850}
2851
2852
2853#undef PyRun_String
2854PyAPI_FUNC(PyObject *)
2855PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002858}
2859
2860#undef PyRun_SimpleString
2861PyAPI_FUNC(int)
2862PyRun_SimpleString(const char *s)
2863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002865}
2866
2867#undef Py_CompileString
2868PyAPI_FUNC(PyObject *)
2869Py_CompileString(const char *str, const char *p, int s)
2870{
Georg Brandl8334fd92010-12-04 10:26:46 +00002871 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2872}
2873
2874#undef Py_CompileStringFlags
2875PyAPI_FUNC(PyObject *)
2876Py_CompileStringFlags(const char *str, const char *p, int s,
2877 PyCompilerFlags *flags)
2878{
2879 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002880}
2881
2882#undef PyRun_InteractiveOne
2883PyAPI_FUNC(int)
2884PyRun_InteractiveOne(FILE *f, const char *p)
2885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002887}
2888
2889#undef PyRun_InteractiveLoop
2890PyAPI_FUNC(int)
2891PyRun_InteractiveLoop(FILE *f, const char *p)
2892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002894}
2895
2896#ifdef __cplusplus
2897}
2898#endif