blob: b963ce1132600908ea078460f836e6d3c6d98b74 [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 Heimes33fe8092008-04-13 13:53:33 +0000119/* PyModule_GetWarningsModule is no longer necessary as of 2.6
120since _warnings is builtin. This API should not be used. */
121PyObject *
122PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000125}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000126
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000128
Thomas Wouters7e474022000-07-16 12:04:32 +0000129/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000130
131int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000132Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000135}
136
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000137/* Helper to allow an embedding application to override the normal
138 * mechanism that attempts to figure out an appropriate IO encoding
139 */
140
141static char *_Py_StandardStreamEncoding = NULL;
142static char *_Py_StandardStreamErrors = NULL;
143
144int
145Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
146{
147 if (Py_IsInitialized()) {
148 /* This is too late to have any effect */
149 return -1;
150 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000151 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
152 * initialised yet.
153 *
154 * However, the raw memory allocators are initialised appropriately
155 * as C static variables, so _PyMem_RawStrdup is OK even though
156 * Py_Initialize hasn't been called yet.
157 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000158 if (encoding) {
159 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
160 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000161 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000162 }
163 }
164 if (errors) {
165 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
166 if (!_Py_StandardStreamErrors) {
167 if (_Py_StandardStreamEncoding) {
168 PyMem_RawFree(_Py_StandardStreamEncoding);
169 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000170 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000171 }
172 }
173 return 0;
174}
175
Guido van Rossum25ce5661997-08-02 03:10:38 +0000176/* Global initializations. Can be undone by Py_Finalize(). Don't
177 call this twice without an intervening Py_Finalize() call. When
178 initializations fail, a fatal error is issued and the function does
179 not return. On return, the first thread and interpreter state have
180 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000181
Guido van Rossum25ce5661997-08-02 03:10:38 +0000182 Locking: you must hold the interpreter lock while calling this.
183 (If the lock has not yet been initialized, that's equivalent to
184 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000185
Guido van Rossum25ce5661997-08-02 03:10:38 +0000186*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000187
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000188static int
189add_flag(int flag, const char *envs)
190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 int env = atoi(envs);
192 if (flag < env)
193 flag = env;
194 if (flag < 1)
195 flag = 1;
196 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000197}
198
Christian Heimes5833a2f2008-10-30 21:40:04 +0000199static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000200get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000201{
Victor Stinner94908bb2010-08-18 21:23:25 +0000202 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000203 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200204 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000205
Victor Stinner94908bb2010-08-18 21:23:25 +0000206 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 if (!codec)
208 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000209
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200210 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 Py_CLEAR(codec);
212 if (!name)
213 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000214
Victor Stinner94908bb2010-08-18 21:23:25 +0000215 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100216 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000217 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200218 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000220 if (name_str == NULL) {
221 PyErr_NoMemory();
222 return NULL;
223 }
224 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000225
226error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000228 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000230}
Victor Stinner94908bb2010-08-18 21:23:25 +0000231
Victor Stinner94908bb2010-08-18 21:23:25 +0000232static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200233get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000234{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200235#ifdef MS_WINDOWS
236 char codepage[100];
237 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
238 return get_codec_name(codepage);
239#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000240 char* codeset = nl_langinfo(CODESET);
241 if (!codeset || codeset[0] == '\0') {
242 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
243 return NULL;
244 }
245 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200246#else
247 PyErr_SetNone(PyExc_NotImplementedError);
248 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000249#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200250}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000251
Brett Cannonfd074152012-04-14 14:10:13 -0400252static void
253import_init(PyInterpreterState *interp, PyObject *sysmod)
254{
255 PyObject *importlib;
256 PyObject *impmod;
257 PyObject *sys_modules;
258 PyObject *value;
259
260 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400261 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
262 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
263 }
264 else if (Py_VerboseFlag) {
265 PySys_FormatStderr("import _frozen_importlib # frozen\n");
266 }
267 importlib = PyImport_AddModule("_frozen_importlib");
268 if (importlib == NULL) {
269 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
270 "sys.modules");
271 }
272 interp->importlib = importlib;
273 Py_INCREF(interp->importlib);
274
275 /* Install _importlib as __import__ */
276 impmod = PyInit_imp();
277 if (impmod == NULL) {
278 Py_FatalError("Py_Initialize: can't import imp");
279 }
280 else if (Py_VerboseFlag) {
281 PySys_FormatStderr("import imp # builtin\n");
282 }
283 sys_modules = PyImport_GetModuleDict();
284 if (Py_VerboseFlag) {
285 PySys_FormatStderr("import sys # builtin\n");
286 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400287 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
288 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400289 }
290
Brett Cannone0d88a12012-04-25 20:54:04 -0400291 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400292 if (value == NULL) {
293 PyErr_Print();
294 Py_FatalError("Py_Initialize: importlib install failed");
295 }
296 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400297 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400298
299 _PyImportZip_Init();
300}
301
302
Guido van Rossuma027efa1997-05-05 20:56:21 +0000303void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200304_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 PyInterpreterState *interp;
307 PyThreadState *tstate;
308 PyObject *bimod, *sysmod, *pstderr;
309 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (initialized)
313 return;
314 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200315 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000316
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000317#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 /* Set up the LC_CTYPE locale, so we can obtain
319 the locale's charset without having to switch
320 locales. */
321 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000322#endif
323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
325 Py_DebugFlag = add_flag(Py_DebugFlag, p);
326 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
327 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
328 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
329 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
330 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
331 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100332 /* The variable is only tested for existence here; _PyRandom_Init will
333 check its value further. */
334 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
335 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
336
337 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 interp = PyInterpreterState_New();
340 if (interp == NULL)
341 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000343 tstate = PyThreadState_New(interp);
344 if (tstate == NULL)
345 Py_FatalError("Py_Initialize: can't make first thread");
346 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000347
Victor Stinner6961bd62010-08-17 22:26:51 +0000348#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000349 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
350 destroying the GIL might fail when it is being referenced from
351 another running thread (see issue #9901).
352 Instead we destroy the previously created GIL here, which ensures
353 that we can call Py_Initialize / Py_Finalize multiple times. */
354 _PyEval_FiniThreads();
355
356 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000357 _PyGILState_Init(interp, tstate);
358#endif /* WITH_THREAD */
359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 if (!_PyFrame_Init())
363 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (!_PyLong_Init())
366 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (!PyByteArray_Init())
369 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000370
Victor Stinner1c8f0592013-07-22 22:24:54 +0200371 if (!_PyFloat_Init())
372 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 interp->modules = PyDict_New();
375 if (interp->modules == NULL)
376 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200379 if (_PyUnicode_Init() < 0)
380 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200381 if (_PyStructSequence_Init() < 0)
382 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 bimod = _PyBuiltin_Init();
385 if (bimod == NULL)
386 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000387 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 interp->builtins = PyModule_GetDict(bimod);
389 if (interp->builtins == NULL)
390 Py_FatalError("Py_Initialize: can't initialize builtins dict");
391 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400394 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 sysmod = _PySys_Init();
397 if (sysmod == NULL)
398 Py_FatalError("Py_Initialize: can't initialize sys");
399 interp->sysdict = PyModule_GetDict(sysmod);
400 if (interp->sysdict == NULL)
401 Py_FatalError("Py_Initialize: can't initialize sys dict");
402 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000403 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 PySys_SetPath(Py_GetPath());
405 PyDict_SetItemString(interp->sysdict, "modules",
406 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 /* Set up a preliminary stderr printer until we have enough
409 infrastructure for the io module in place. */
410 pstderr = PyFile_NewStdPrinter(fileno(stderr));
411 if (pstderr == NULL)
412 Py_FatalError("Py_Initialize: can't set preliminary stderr");
413 PySys_SetObject("stderr", pstderr);
414 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000415 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000420
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000421 /* Initialize _warnings. */
422 _PyWarnings_Init();
423
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200424 if (!install_importlib)
425 return;
426
Brett Cannonfd074152012-04-14 14:10:13 -0400427 import_init(interp, sysmod);
428
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200429 /* initialize the faulthandler module */
430 if (_PyFaulthandler_Init())
431 Py_FatalError("Py_Initialize: can't initialize faulthandler");
432
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000433 _PyTime_Init();
434
Victor Stinner793b5312011-04-27 00:24:21 +0200435 if (initfsencoding(interp) < 0)
436 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (install_sigs)
439 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000440
Nick Coghlan85e729e2012-07-15 18:09:52 +1000441 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 if (initstdio() < 0)
443 Py_FatalError(
444 "Py_Initialize: can't initialize sys standard streams");
445
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000446 /* Initialize warnings. */
447 if (PySys_HasWarnOptions()) {
448 PyObject *warnings_module = PyImport_ImportModule("warnings");
449 if (warnings_module == NULL) {
450 fprintf(stderr, "'import warnings' failed; traceback:\n");
451 PyErr_Print();
452 }
453 Py_XDECREF(warnings_module);
454 }
455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (!Py_NoSiteFlag)
457 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000458}
459
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000460void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200461Py_InitializeEx(int install_sigs)
462{
463 _Py_InitializeEx_Private(install_sigs, 1);
464}
465
466void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000467Py_Initialize(void)
468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000470}
471
472
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000473#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000474extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000475#endif
476
Guido van Rossume8432ac2007-07-09 15:04:50 +0000477/* Flush stdout and stderr */
478
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100479static int
480file_is_closed(PyObject *fobj)
481{
482 int r;
483 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
484 if (tmp == NULL) {
485 PyErr_Clear();
486 return 0;
487 }
488 r = PyObject_IsTrue(tmp);
489 Py_DECREF(tmp);
490 if (r < 0)
491 PyErr_Clear();
492 return r > 0;
493}
494
Neal Norwitz2bad9702007-08-27 06:19:22 +0000495static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000496flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 PyObject *fout = PySys_GetObject("stdout");
499 PyObject *ferr = PySys_GetObject("stderr");
500 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200501 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000502
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100503 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200504 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000506 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 else
508 Py_DECREF(tmp);
509 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000510
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100511 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200512 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (tmp == NULL)
514 PyErr_Clear();
515 else
516 Py_DECREF(tmp);
517 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000518}
519
Guido van Rossum25ce5661997-08-02 03:10:38 +0000520/* Undo the effect of Py_Initialize().
521
522 Beware: if multiple interpreter and/or thread states exist, these
523 are not wiped out; only the current thread and interpreter state
524 are deleted. But since everything else is deleted, those other
525 interpreter and thread states should no longer be used.
526
527 (XXX We should do better, e.g. wipe out all interpreters and
528 threads.)
529
530 Locking: as above.
531
532*/
533
534void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000535Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 PyInterpreterState *interp;
538 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 if (!initialized)
541 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 /* The interpreter is still entirely intact at this point, and the
546 * exit funcs may be relying on that. In particular, if some thread
547 * or exit func is still waiting to do an import, the import machinery
548 * expects Py_IsInitialized() to return true. So don't say the
549 * interpreter is uninitialized until after the exit funcs have run.
550 * Note that Threading.py uses an exit func to do a join on all the
551 * threads created thru it, so this also protects pending imports in
552 * the threads created via Threading.
553 */
554 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 /* Get current thread state and interpreter pointer */
557 tstate = PyThreadState_GET();
558 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200560 /* Remaining threads (e.g. daemon threads) will automatically exit
561 after taking the GIL (in PyEval_RestoreThread()). */
562 _Py_Finalizing = tstate;
563 initialized = 0;
564
565 /* Flush stdout+stderr */
566 flush_std_files();
567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 /* Disable signal handling */
569 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 /* Collect garbage. This may call finalizers; it's nice to call these
572 * before all modules are destroyed.
573 * XXX If a __del__ or weakref callback is triggered here, and tries to
574 * XXX import a module, bad things can happen, because Python no
575 * XXX longer believes it's initialized.
576 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
577 * XXX is easy to provoke that way. I've also seen, e.g.,
578 * XXX Exception exceptions.ImportError: 'No module named sha'
579 * XXX in <function callback at 0x008F5718> ignored
580 * XXX but I'm unclear on exactly how that one happens. In any case,
581 * XXX I haven't seen a real-life report of either of these.
582 */
583 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000584#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 /* With COUNT_ALLOCS, it helps to run GC multiple times:
586 each collection might release some types from the type
587 list, so they become garbage. */
588 while (PyGC_Collect() > 0)
589 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000590#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 /* Destroy all modules */
592 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 /* Flush stdout+stderr (again, in case more was printed) */
595 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100598 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 * XXX This is disabled because it caused too many problems. If
600 * XXX a __del__ or weakref callback triggers here, Python code has
601 * XXX a hard time running, because even the sys module has been
602 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
603 * XXX One symptom is a sequence of information-free messages
604 * XXX coming from threads (if a __del__ or callback is invoked,
605 * XXX other threads can execute too, and any exception they encounter
606 * XXX triggers a comedy of errors as subsystem after subsystem
607 * XXX fails to find what it *expects* to find in sys to help report
608 * XXX the exception and consequent unexpected failures). I've also
609 * XXX seen segfaults then, after adding print statements to the
610 * XXX Python code getting called.
611 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000612#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000614#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
617 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000618
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200619 /* Cleanup typeobject.c's internal caches. */
620 _PyType_Fini();
621
Victor Stinner024e37a2011-03-31 01:31:06 +0200622 /* unload faulthandler module */
623 _PyFaulthandler_Fini();
624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000626#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000628#endif
629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000631
Tim Peters9cf25ce2003-04-17 15:21:01 +0000632#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 /* Display all objects still alive -- this can invoke arbitrary
634 * __repr__ overrides, so requires a mostly-intact interpreter.
635 * Alas, a lot of stuff may still be alive now that will be cleaned
636 * up later.
637 */
638 if (Py_GETENV("PYTHONDUMPREFS"))
639 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000640#endif /* Py_TRACE_REFS */
641
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200642 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 /* Now we decref the exception classes. After this point nothing
646 can raise an exception. That's okay, because each Fini() method
647 below has been checked to make sure no exceptions are ever
648 raised.
649 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 /* Sundry finalizers */
654 PyMethod_Fini();
655 PyFrame_Fini();
656 PyCFunction_Fini();
657 PyTuple_Fini();
658 PyList_Fini();
659 PySet_Fini();
660 PyBytes_Fini();
661 PyByteArray_Fini();
662 PyLong_Fini();
663 PyFloat_Fini();
664 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100665 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200666 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200667 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 /* Cleanup Unicode implementation */
670 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000673 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200674 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 Py_FileSystemDefaultEncoding = NULL;
676 }
Christian Heimesc8967002007-11-30 10:18:26 +0000677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 /* XXX Still allocated:
679 - various static ad-hoc pointers to interned strings
680 - int and float free list blocks
681 - whatever various modules and libraries allocate
682 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000685
Victor Stinner51fa4582013-07-07 15:50:49 +0200686 /* Cleanup auto-thread-state */
687#ifdef WITH_THREAD
688 _PyGILState_Fini();
689#endif /* WITH_THREAD */
690
691 /* Delete current thread. After this, many C API calls become crashy. */
692 PyThreadState_Swap(NULL);
693 PyInterpreterState_Delete(interp);
694
Tim Peters269b2a62003-04-17 19:52:29 +0000695#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 /* Display addresses (& refcnts) of all objects still alive.
697 * An address can be used to find the repr of the object, printed
698 * above by _Py_PrintReferences.
699 */
700 if (Py_GETENV("PYTHONDUMPREFS"))
701 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000702#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000703#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400705 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000706#endif
707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000709}
710
711/* Create and initialize a new interpreter and thread, and return the
712 new thread. This requires that Py_Initialize() has been called
713 first.
714
715 Unsuccessful initialization yields a NULL pointer. Note that *no*
716 exception information is available even in this case -- the
717 exception information is held in the thread, and there is no
718 thread.
719
720 Locking: as above.
721
722*/
723
724PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000725Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 PyInterpreterState *interp;
728 PyThreadState *tstate, *save_tstate;
729 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 if (!initialized)
732 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 interp = PyInterpreterState_New();
735 if (interp == NULL)
736 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 tstate = PyThreadState_New(interp);
739 if (tstate == NULL) {
740 PyInterpreterState_Delete(interp);
741 return NULL;
742 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000749
Victor Stinner49d3f252010-10-17 01:24:53 +0000750 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (bimod != NULL) {
752 interp->builtins = PyModule_GetDict(bimod);
753 if (interp->builtins == NULL)
754 goto handle_error;
755 Py_INCREF(interp->builtins);
756 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400759 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000760
Victor Stinner49d3f252010-10-17 01:24:53 +0000761 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 if (bimod != NULL && sysmod != NULL) {
763 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 interp->sysdict = PyModule_GetDict(sysmod);
766 if (interp->sysdict == NULL)
767 goto handle_error;
768 Py_INCREF(interp->sysdict);
769 PySys_SetPath(Py_GetPath());
770 PyDict_SetItemString(interp->sysdict, "modules",
771 interp->modules);
772 /* Set up a preliminary stderr printer until we have enough
773 infrastructure for the io module in place. */
774 pstderr = PyFile_NewStdPrinter(fileno(stderr));
775 if (pstderr == NULL)
776 Py_FatalError("Py_Initialize: can't set preliminary stderr");
777 PySys_SetObject("stderr", pstderr);
778 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000779 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200782
Brett Cannonfd074152012-04-14 14:10:13 -0400783 import_init(interp, sysmod);
784
Victor Stinner793b5312011-04-27 00:24:21 +0200785 if (initfsencoding(interp) < 0)
786 goto handle_error;
787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 if (initstdio() < 0)
789 Py_FatalError(
790 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000791 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 if (!Py_NoSiteFlag)
793 initsite();
794 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (!PyErr_Occurred())
797 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000798
Thomas Wouters89f507f2006-12-13 04:49:30 +0000799handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000801
Victor Stinnerc40a3502011-04-27 00:20:27 +0200802 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 PyThreadState_Clear(tstate);
804 PyThreadState_Swap(save_tstate);
805 PyThreadState_Delete(tstate);
806 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000809}
810
811/* Delete an interpreter and its last thread. This requires that the
812 given thread state is current, that the thread has no remaining
813 frames, and that it is its interpreter's only remaining thread.
814 It is a fatal error to violate these constraints.
815
816 (Py_Finalize() doesn't have these constraints -- it zaps
817 everything, regardless.)
818
819 Locking: as above.
820
821*/
822
823void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000824Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 if (tstate != PyThreadState_GET())
829 Py_FatalError("Py_EndInterpreter: thread is not current");
830 if (tstate->frame != NULL)
831 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200832
833 wait_for_thread_shutdown();
834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 if (tstate != interp->tstate_head || tstate->next != NULL)
836 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyImport_Cleanup();
839 PyInterpreterState_Clear(interp);
840 PyThreadState_Swap(NULL);
841 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000842}
843
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200844#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000845static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200846#else
847static wchar_t *progname = L"python3";
848#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000849
850void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000851Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 if (pn && *pn)
854 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000855}
856
Martin v. Löwis790465f2008-04-05 20:41:37 +0000857wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000858Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000861}
862
Martin v. Löwis790465f2008-04-05 20:41:37 +0000863static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200864static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000865
866void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000867Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000870}
871
Martin v. Löwis790465f2008-04-05 20:41:37 +0000872wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000873Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 wchar_t *home = default_home;
876 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
877 char* chome = Py_GETENV("PYTHONHOME");
878 if (chome) {
879 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
880 if (r != (size_t)-1 && r <= PATH_MAX)
881 home = env_home;
882 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 }
885 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000886}
887
Guido van Rossum6135a871995-01-09 17:53:26 +0000888/* Create __main__ module */
889
890static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000891initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000892{
Brett Cannon13853a62013-05-04 17:37:09 -0400893 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 m = PyImport_AddModule("__main__");
895 if (m == NULL)
896 Py_FatalError("can't create __main__ module");
897 d = PyModule_GetDict(m);
898 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
899 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000900 if (bimod == NULL) {
901 Py_FatalError("Failed to retrieve builtins module");
902 }
903 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
904 Py_FatalError("Failed to initialize __main__.__builtins__");
905 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 Py_DECREF(bimod);
907 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000908 /* Main is a little special - imp.is_builtin("__main__") will return
909 * False, but BuiltinImporter is still the most appropriate initial
910 * setting for its __loader__ attribute. A more suitable value will
911 * be set if __main__ gets further initialized later in the startup
912 * process.
913 */
Brett Cannon13853a62013-05-04 17:37:09 -0400914 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400915 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000916 PyObject *loader = PyObject_GetAttrString(interp->importlib,
917 "BuiltinImporter");
918 if (loader == NULL) {
919 Py_FatalError("Failed to retrieve BuiltinImporter");
920 }
921 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
922 Py_FatalError("Failed to initialize __main__.__loader__");
923 }
924 Py_DECREF(loader);
925 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000926}
927
Victor Stinner793b5312011-04-27 00:24:21 +0200928static int
929initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000930{
931 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000932
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200933 if (Py_FileSystemDefaultEncoding == NULL)
934 {
935 Py_FileSystemDefaultEncoding = get_locale_encoding();
936 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000937 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000938
Victor Stinnere4743092010-10-19 00:05:51 +0000939 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200940 interp->fscodec_initialized = 1;
941 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000942 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000943
944 /* the encoding is mbcs, utf-8 or ascii */
945 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
946 if (!codec) {
947 /* Such error can only occurs in critical situations: no more
948 * memory, import a module of the standard library failed,
949 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200950 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000951 }
Victor Stinner793b5312011-04-27 00:24:21 +0200952 Py_DECREF(codec);
953 interp->fscodec_initialized = 1;
954 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000955}
956
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000957/* Import the site module (not into __main__ though) */
958
959static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000960initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 PyObject *m;
963 m = PyImport_ImportModule("site");
964 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200965 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 PyErr_Print();
967 Py_Finalize();
968 exit(1);
969 }
970 else {
971 Py_DECREF(m);
972 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000973}
974
Antoine Pitrou05608432009-01-09 18:53:14 +0000975static PyObject*
976create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 int fd, int write_mode, char* name,
978 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
981 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000982 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyObject *line_buffering;
984 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200985 _Py_IDENTIFIER(open);
986 _Py_IDENTIFIER(isatty);
987 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200988 _Py_IDENTIFIER(name);
989 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 /* stdin is always opened in buffered mode, first because it shouldn't
992 make a difference in common use cases, second because TextIOWrapper
993 depends on the presence of a read1() method which only exists on
994 buffered streams.
995 */
996 if (Py_UnbufferedStdioFlag && write_mode)
997 buffering = 0;
998 else
999 buffering = -1;
1000 if (write_mode)
1001 mode = "wb";
1002 else
1003 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001004 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1005 fd, mode, buffering,
1006 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (buf == NULL)
1008 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001011 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001012 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (raw == NULL)
1014 goto error;
1015 }
1016 else {
1017 raw = buf;
1018 Py_INCREF(raw);
1019 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001022 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001024 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (res == NULL)
1026 goto error;
1027 isatty = PyObject_IsTrue(res);
1028 Py_DECREF(res);
1029 if (isatty == -1)
1030 goto error;
1031 if (isatty || Py_UnbufferedStdioFlag)
1032 line_buffering = Py_True;
1033 else
1034 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 Py_CLEAR(raw);
1037 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001038
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001039#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001040 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1041 newlines to "\n".
1042 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1043 newline = NULL;
1044#else
1045 /* sys.stdin: split lines at "\n".
1046 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1047 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001048#endif
1049
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001050 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1051 buf, encoding, errors,
1052 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 Py_CLEAR(buf);
1054 if (stream == NULL)
1055 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 if (write_mode)
1058 mode = "w";
1059 else
1060 mode = "r";
1061 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001062 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 goto error;
1064 Py_CLEAR(text);
1065 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001066
1067error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 Py_XDECREF(buf);
1069 Py_XDECREF(stream);
1070 Py_XDECREF(text);
1071 Py_XDECREF(raw);
1072 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001073}
1074
Antoine Pitrou11942a52011-11-28 19:08:36 +01001075static int
1076is_valid_fd(int fd)
1077{
1078 int dummy_fd;
1079 if (fd < 0 || !_PyVerify_fd(fd))
1080 return 0;
1081 dummy_fd = dup(fd);
1082 if (dummy_fd < 0)
1083 return 0;
1084 close(dummy_fd);
1085 return 1;
1086}
1087
Georg Brandl1a3284e2007-12-02 09:40:06 +00001088/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001089static int
1090initstdio(void)
1091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyObject *iomod = NULL, *wrapper;
1093 PyObject *bimod = NULL;
1094 PyObject *m;
1095 PyObject *std = NULL;
1096 int status = 0, fd;
1097 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001098 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 /* Hack to avoid a nasty recursion issue when Python is invoked
1101 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1102 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1103 goto error;
1104 }
1105 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1108 goto error;
1109 }
1110 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 if (!(bimod = PyImport_ImportModule("builtins"))) {
1113 goto error;
1114 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (!(iomod = PyImport_ImportModule("io"))) {
1117 goto error;
1118 }
1119 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1120 goto error;
1121 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 /* Set builtins.open */
1124 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001125 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 goto error;
1127 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001128 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001129
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001130 encoding = _Py_StandardStreamEncoding;
1131 errors = _Py_StandardStreamErrors;
1132 if (!encoding || !errors) {
1133 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1134 if (pythonioencoding) {
1135 char *err;
1136 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1137 if (pythonioencoding == NULL) {
1138 PyErr_NoMemory();
1139 goto error;
1140 }
1141 err = strchr(pythonioencoding, ':');
1142 if (err) {
1143 *err = '\0';
1144 err++;
1145 if (*err && !errors) {
1146 errors = err;
1147 }
1148 }
1149 if (*pythonioencoding && !encoding) {
1150 encoding = pythonioencoding;
1151 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001152 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 /* Set sys.stdin */
1156 fd = fileno(stdin);
1157 /* Under some conditions stdin, stdout and stderr may not be connected
1158 * and fileno() may point to an invalid file descriptor. For example
1159 * GUI apps don't have valid standard streams by default.
1160 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001161 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 std = Py_None;
1163 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 }
1165 else {
1166 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1167 if (std == NULL)
1168 goto error;
1169 } /* if (fd < 0) */
1170 PySys_SetObject("__stdin__", std);
1171 PySys_SetObject("stdin", std);
1172 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 /* Set sys.stdout */
1175 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001176 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 std = Py_None;
1178 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 }
1180 else {
1181 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1182 if (std == NULL)
1183 goto error;
1184 } /* if (fd < 0) */
1185 PySys_SetObject("__stdout__", std);
1186 PySys_SetObject("stdout", std);
1187 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001188
Guido van Rossum98297ee2007-11-06 21:34:58 +00001189#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 /* Set sys.stderr, replaces the preliminary stderr */
1191 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001192 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 std = Py_None;
1194 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 }
1196 else {
1197 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1198 if (std == NULL)
1199 goto error;
1200 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 /* Same as hack above, pre-import stderr's codec to avoid recursion
1203 when import.c tries to write to stderr in verbose mode. */
1204 encoding_attr = PyObject_GetAttrString(std, "encoding");
1205 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001206 const char * std_encoding;
1207 std_encoding = _PyUnicode_AsString(encoding_attr);
1208 if (std_encoding != NULL) {
1209 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001210 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001212 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
1214 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001215
Victor Stinnerba308832013-07-22 23:55:19 +02001216 if (PySys_SetObject("__stderr__", std) < 0) {
1217 Py_DECREF(std);
1218 goto error;
1219 }
1220 if (PySys_SetObject("stderr", std) < 0) {
1221 Py_DECREF(std);
1222 goto error;
1223 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001225#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001228 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 status = -1;
1230 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001231
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001232 /* We won't need them anymore. */
1233 if (_Py_StandardStreamEncoding) {
1234 PyMem_RawFree(_Py_StandardStreamEncoding);
1235 _Py_StandardStreamEncoding = NULL;
1236 }
1237 if (_Py_StandardStreamErrors) {
1238 PyMem_RawFree(_Py_StandardStreamErrors);
1239 _Py_StandardStreamErrors = NULL;
1240 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001241 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 Py_XDECREF(bimod);
1243 Py_XDECREF(iomod);
1244 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001245}
1246
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001247/* Parse input from a file and execute it */
1248
1249int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001250PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 if (filename == NULL)
1254 filename = "???";
1255 if (Py_FdIsInteractive(fp, filename)) {
1256 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1257 if (closeit)
1258 fclose(fp);
1259 return err;
1260 }
1261 else
1262 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001263}
1264
1265int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001266PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 PyObject *v;
1269 int ret;
1270 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 if (flags == NULL) {
1273 flags = &local_flags;
1274 local_flags.cf_flags = 0;
1275 }
1276 v = PySys_GetObject("ps1");
1277 if (v == NULL) {
1278 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1279 Py_XDECREF(v);
1280 }
1281 v = PySys_GetObject("ps2");
1282 if (v == NULL) {
1283 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1284 Py_XDECREF(v);
1285 }
1286 for (;;) {
1287 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1288 PRINT_TOTAL_REFS();
1289 if (ret == E_EOF)
1290 return 0;
1291 /*
1292 if (ret == E_NOMEM)
1293 return -1;
1294 */
1295 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001296}
1297
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001298/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001299static int PARSER_FLAGS(PyCompilerFlags *flags)
1300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 int parser_flags = 0;
1302 if (!flags)
1303 return 0;
1304 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1305 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1306 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1307 parser_flags |= PyPARSE_IGNORE_COOKIE;
1308 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1309 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1310 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001311}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001312
Thomas Wouters89f507f2006-12-13 04:49:30 +00001313#if 0
1314/* Keep an example of flags with future keyword support. */
1315#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1317 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1318 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1319 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001320#endif
1321
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001322int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001323PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 PyObject *m, *d, *v, *w, *oenc = NULL;
1326 mod_ty mod;
1327 PyArena *arena;
1328 char *ps1 = "", *ps2 = "", *enc = NULL;
1329 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001330 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001333 /* Fetch encoding from sys.stdin if possible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 v = PySys_GetObject("stdin");
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001335 if (v && v != Py_None) {
1336 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1337 if (oenc)
1338 enc = _PyUnicode_AsString(oenc);
1339 if (!enc)
1340 PyErr_Clear();
1341 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 }
1343 v = PySys_GetObject("ps1");
1344 if (v != NULL) {
1345 v = PyObject_Str(v);
1346 if (v == NULL)
1347 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001348 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001350 if (ps1 == NULL) {
1351 PyErr_Clear();
1352 ps1 = "";
1353 }
1354 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 }
1356 w = PySys_GetObject("ps2");
1357 if (w != NULL) {
1358 w = PyObject_Str(w);
1359 if (w == NULL)
1360 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001361 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001363 if (ps2 == NULL) {
1364 PyErr_Clear();
1365 ps2 = "";
1366 }
1367 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 }
1369 arena = PyArena_New();
1370 if (arena == NULL) {
1371 Py_XDECREF(v);
1372 Py_XDECREF(w);
1373 Py_XDECREF(oenc);
1374 return -1;
1375 }
1376 mod = PyParser_ASTFromFile(fp, filename, enc,
1377 Py_single_input, ps1, ps2,
1378 flags, &errcode, arena);
1379 Py_XDECREF(v);
1380 Py_XDECREF(w);
1381 Py_XDECREF(oenc);
1382 if (mod == NULL) {
1383 PyArena_Free(arena);
1384 if (errcode == E_EOF) {
1385 PyErr_Clear();
1386 return E_EOF;
1387 }
1388 PyErr_Print();
1389 return -1;
1390 }
1391 m = PyImport_AddModule("__main__");
1392 if (m == NULL) {
1393 PyArena_Free(arena);
1394 return -1;
1395 }
1396 d = PyModule_GetDict(m);
1397 v = run_mod(mod, filename, d, d, flags, arena);
1398 PyArena_Free(arena);
1399 flush_io();
1400 if (v == NULL) {
1401 PyErr_Print();
1402 return -1;
1403 }
1404 Py_DECREF(v);
1405 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001406}
1407
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001408/* Check whether a file maybe a pyc file: Look at the extension,
1409 the file type, and, if we may close it, at the first few bytes. */
1410
1411static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001412maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1415 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 /* Only look into the file if we are allowed to close it, since
1418 it then should also be seekable. */
1419 if (closeit) {
1420 /* Read only two bytes of the magic. If the file was opened in
1421 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1422 be read as they are on disk. */
1423 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1424 unsigned char buf[2];
1425 /* Mess: In case of -x, the stream is NOT at its start now,
1426 and ungetc() was used to push back the first newline,
1427 which makes the current stream position formally undefined,
1428 and a x-platform nightmare.
1429 Unfortunately, we have no direct way to know whether -x
1430 was specified. So we use a terrible hack: if the current
1431 stream position is not 0, we assume -x was specified, and
1432 give up. Bug 132850 on SourceForge spells out the
1433 hopelessness of trying anything else (fseek and ftell
1434 don't work predictably x-platform for text-mode files).
1435 */
1436 int ispyc = 0;
1437 if (ftell(fp) == 0) {
1438 if (fread(buf, 1, 2, fp) == 2 &&
1439 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1440 ispyc = 1;
1441 rewind(fp);
1442 }
1443 return ispyc;
1444 }
1445 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001446}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001447
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001448static int
1449set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001450{
1451 PyInterpreterState *interp;
1452 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001453 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001454 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001455
1456 filename_obj = PyUnicode_DecodeFSDefault(filename);
1457 if (filename_obj == NULL)
1458 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001459 /* Get current thread state and interpreter pointer */
1460 tstate = PyThreadState_GET();
1461 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001462 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1463 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001464 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001465 return -1;
1466 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001467 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001468 Py_DECREF(loader_type);
1469 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001470 return -1;
1471 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001472 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1473 result = -1;
1474 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001475 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001476 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001477}
1478
1479int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001480PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 PyObject *m, *d, *v;
1484 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001485 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001486 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 m = PyImport_AddModule("__main__");
1489 if (m == NULL)
1490 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001491 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 d = PyModule_GetDict(m);
1493 if (PyDict_GetItemString(d, "__file__") == NULL) {
1494 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001495 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001497 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1499 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001500 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001502 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1503 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001504 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001505 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 set_file_name = 1;
1507 Py_DECREF(f);
1508 }
1509 len = strlen(filename);
1510 ext = filename + len - (len > 4 ? 4 : 0);
1511 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001512 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 /* Try to run a pyc file. First, re-open in binary */
1514 if (closeit)
1515 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001516 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 goto done;
1519 }
1520 /* Turn on optimization if a .pyo file is given */
1521 if (strcmp(ext, ".pyo") == 0)
1522 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001523
1524 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1525 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1526 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001527 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001528 goto done;
1529 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001530 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1531 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001533 /* When running from stdin, leave __main__.__loader__ alone */
1534 if (strcmp(filename, "<stdin>") != 0 &&
1535 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1536 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1537 ret = -1;
1538 goto done;
1539 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1541 closeit, flags);
1542 }
1543 flush_io();
1544 if (v == NULL) {
1545 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 goto done;
1547 }
1548 Py_DECREF(v);
1549 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001550 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1552 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001553 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001555}
1556
1557int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001558PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 PyObject *m, *d, *v;
1561 m = PyImport_AddModule("__main__");
1562 if (m == NULL)
1563 return -1;
1564 d = PyModule_GetDict(m);
1565 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1566 if (v == NULL) {
1567 PyErr_Print();
1568 return -1;
1569 }
1570 Py_DECREF(v);
1571 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001572}
1573
Barry Warsaw035574d1997-08-29 22:07:17 +00001574static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001575parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 long hold;
1579 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001580 _Py_IDENTIFIER(msg);
1581 _Py_IDENTIFIER(filename);
1582 _Py_IDENTIFIER(lineno);
1583 _Py_IDENTIFIER(offset);
1584 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001585
Benjamin Peterson80d50422012-04-03 00:30:38 -04001586 *message = NULL;
1587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001589 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001590 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001592
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001593 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001594 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001596 if (v == Py_None) {
1597 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001599 }
1600 else {
1601 *filename = _PyUnicode_AsString(v);
1602 Py_DECREF(v);
1603 if (!*filename)
1604 goto finally;
1605 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001606
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001607 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001608 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 goto finally;
1610 hold = PyLong_AsLong(v);
1611 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 if (hold < 0 && PyErr_Occurred())
1613 goto finally;
1614 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001615
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001616 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001617 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 goto finally;
1619 if (v == Py_None) {
1620 *offset = -1;
1621 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 } else {
1623 hold = PyLong_AsLong(v);
1624 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (hold < 0 && PyErr_Occurred())
1626 goto finally;
1627 *offset = (int)hold;
1628 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001629
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001630 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001631 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001633 if (v == Py_None) {
1634 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001636 }
1637 else {
1638 *text = _PyUnicode_AsString(v);
1639 Py_DECREF(v);
1640 if (!*text)
1641 goto finally;
1642 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001644
1645finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001646 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001648}
1649
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001650void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001651PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001654}
1655
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001656static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001657print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 char *nl;
1660 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001661 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1662 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 for (;;) {
1664 nl = strchr(text, '\n');
1665 if (nl == NULL || nl-text >= offset)
1666 break;
1667 offset -= (int)(nl+1-text);
1668 text = nl+1;
1669 }
1670 while (*text == ' ' || *text == '\t') {
1671 text++;
1672 offset--;
1673 }
1674 }
1675 PyFile_WriteString(" ", f);
1676 PyFile_WriteString(text, f);
1677 if (*text == '\0' || text[strlen(text)-1] != '\n')
1678 PyFile_WriteString("\n", f);
1679 if (offset == -1)
1680 return;
1681 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001682 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001685}
1686
Guido van Rossum66e8e862001-03-23 17:54:43 +00001687static void
1688handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 PyObject *exception, *value, *tb;
1691 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 if (Py_InspectFlag)
1694 /* Don't exit if -i flag was given. This flag is set to 0
1695 * when entering interactive mode for inspecting. */
1696 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 PyErr_Fetch(&exception, &value, &tb);
1699 fflush(stdout);
1700 if (value == NULL || value == Py_None)
1701 goto done;
1702 if (PyExceptionInstance_Check(value)) {
1703 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001704 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001705 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 if (code) {
1707 Py_DECREF(value);
1708 value = code;
1709 if (value == Py_None)
1710 goto done;
1711 }
1712 /* If we failed to dig out the 'code' attribute,
1713 just let the else clause below print the error. */
1714 }
1715 if (PyLong_Check(value))
1716 exitcode = (int)PyLong_AsLong(value);
1717 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001718 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001719 if (sys_stderr != NULL && sys_stderr != Py_None) {
1720 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1721 } else {
1722 PyObject_Print(value, stderr, Py_PRINT_RAW);
1723 fflush(stderr);
1724 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 PySys_WriteStderr("\n");
1726 exitcode = 1;
1727 }
Tim Peterscf615b52003-04-19 18:47:02 +00001728 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 /* Restore and clear the exception info, in order to properly decref
1730 * the exception, value, and traceback. If we just exit instead,
1731 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1732 * some finalizers from running.
1733 */
1734 PyErr_Restore(exception, value, tb);
1735 PyErr_Clear();
1736 Py_Exit(exitcode);
1737 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001738}
1739
1740void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001741PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1746 handle_system_exit();
1747 }
1748 PyErr_Fetch(&exception, &v, &tb);
1749 if (exception == NULL)
1750 return;
1751 PyErr_NormalizeException(&exception, &v, &tb);
1752 if (tb == NULL) {
1753 tb = Py_None;
1754 Py_INCREF(tb);
1755 }
1756 PyException_SetTraceback(v, tb);
1757 if (exception == NULL)
1758 return;
1759 /* Now we know v != NULL too */
1760 if (set_sys_last_vars) {
1761 PySys_SetObject("last_type", exception);
1762 PySys_SetObject("last_value", v);
1763 PySys_SetObject("last_traceback", tb);
1764 }
1765 hook = PySys_GetObject("excepthook");
1766 if (hook) {
1767 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1768 PyObject *result = PyEval_CallObject(hook, args);
1769 if (result == NULL) {
1770 PyObject *exception2, *v2, *tb2;
1771 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1772 handle_system_exit();
1773 }
1774 PyErr_Fetch(&exception2, &v2, &tb2);
1775 PyErr_NormalizeException(&exception2, &v2, &tb2);
1776 /* It should not be possible for exception2 or v2
1777 to be NULL. However PyErr_Display() can't
1778 tolerate NULLs, so just be safe. */
1779 if (exception2 == NULL) {
1780 exception2 = Py_None;
1781 Py_INCREF(exception2);
1782 }
1783 if (v2 == NULL) {
1784 v2 = Py_None;
1785 Py_INCREF(v2);
1786 }
1787 fflush(stdout);
1788 PySys_WriteStderr("Error in sys.excepthook:\n");
1789 PyErr_Display(exception2, v2, tb2);
1790 PySys_WriteStderr("\nOriginal exception was:\n");
1791 PyErr_Display(exception, v, tb);
1792 Py_DECREF(exception2);
1793 Py_DECREF(v2);
1794 Py_XDECREF(tb2);
1795 }
1796 Py_XDECREF(result);
1797 Py_XDECREF(args);
1798 } else {
1799 PySys_WriteStderr("sys.excepthook is missing\n");
1800 PyErr_Display(exception, v, tb);
1801 }
1802 Py_XDECREF(exception);
1803 Py_XDECREF(v);
1804 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001805}
1806
Benjamin Petersone6528212008-07-15 15:32:09 +00001807static void
1808print_exception(PyObject *f, PyObject *value)
1809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 int err = 0;
1811 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001812 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 if (!PyExceptionInstance_Check(value)) {
1815 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1816 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1817 PyFile_WriteString(" found\n", f);
1818 return;
1819 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 Py_INCREF(value);
1822 fflush(stdout);
1823 type = (PyObject *) Py_TYPE(value);
1824 tb = PyException_GetTraceback(value);
1825 if (tb && tb != Py_None)
1826 err = PyTraceBack_Print(tb, f);
1827 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001828 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 {
1830 PyObject *message;
1831 const char *filename, *text;
1832 int lineno, offset;
1833 if (!parse_syntax_error(value, &message, &filename,
1834 &lineno, &offset, &text))
1835 PyErr_Clear();
1836 else {
1837 char buf[10];
1838 PyFile_WriteString(" File \"", f);
1839 if (filename == NULL)
1840 PyFile_WriteString("<string>", f);
1841 else
1842 PyFile_WriteString(filename, f);
1843 PyFile_WriteString("\", line ", f);
1844 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1845 PyFile_WriteString(buf, f);
1846 PyFile_WriteString("\n", f);
1847 if (text != NULL)
1848 print_error_text(f, offset, text);
1849 Py_DECREF(value);
1850 value = message;
1851 /* Can't be bothered to check all those
1852 PyFile_WriteString() calls */
1853 if (PyErr_Occurred())
1854 err = -1;
1855 }
1856 }
1857 if (err) {
1858 /* Don't do anything else */
1859 }
1860 else {
1861 PyObject* moduleName;
1862 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001863 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 assert(PyExceptionClass_Check(type));
1865 className = PyExceptionClass_Name(type);
1866 if (className != NULL) {
1867 char *dot = strrchr(className, '.');
1868 if (dot != NULL)
1869 className = dot+1;
1870 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001871
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001872 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1874 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001875 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 err = PyFile_WriteString("<unknown>", f);
1877 }
1878 else {
1879 char* modstr = _PyUnicode_AsString(moduleName);
1880 if (modstr && strcmp(modstr, "builtins"))
1881 {
1882 err = PyFile_WriteString(modstr, f);
1883 err += PyFile_WriteString(".", f);
1884 }
1885 Py_DECREF(moduleName);
1886 }
1887 if (err == 0) {
1888 if (className == NULL)
1889 err = PyFile_WriteString("<unknown>", f);
1890 else
1891 err = PyFile_WriteString(className, f);
1892 }
1893 }
1894 if (err == 0 && (value != Py_None)) {
1895 PyObject *s = PyObject_Str(value);
1896 /* only print colon if the str() of the
1897 object is not the empty string
1898 */
1899 if (s == NULL)
1900 err = -1;
1901 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001902 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 err = PyFile_WriteString(": ", f);
1904 if (err == 0)
1905 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1906 Py_XDECREF(s);
1907 }
1908 /* try to write a newline in any case */
1909 err += PyFile_WriteString("\n", f);
1910 Py_XDECREF(tb);
1911 Py_DECREF(value);
1912 /* If an error happened here, don't show it.
1913 XXX This is wrong, but too many callers rely on this behavior. */
1914 if (err != 0)
1915 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001916}
1917
1918static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 "\nThe above exception was the direct cause "
1920 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001921
1922static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 "\nDuring handling of the above exception, "
1924 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001925
1926static void
1927print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 int err = 0, res;
1930 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 if (seen != NULL) {
1933 /* Exception chaining */
1934 if (PySet_Add(seen, value) == -1)
1935 PyErr_Clear();
1936 else if (PyExceptionInstance_Check(value)) {
1937 cause = PyException_GetCause(value);
1938 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001939 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 res = PySet_Contains(seen, cause);
1941 if (res == -1)
1942 PyErr_Clear();
1943 if (res == 0) {
1944 print_exception_recursive(
1945 f, cause, seen);
1946 err |= PyFile_WriteString(
1947 cause_message, f);
1948 }
1949 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001950 else if (context &&
1951 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001952 res = PySet_Contains(seen, context);
1953 if (res == -1)
1954 PyErr_Clear();
1955 if (res == 0) {
1956 print_exception_recursive(
1957 f, context, seen);
1958 err |= PyFile_WriteString(
1959 context_message, f);
1960 }
1961 }
1962 Py_XDECREF(context);
1963 Py_XDECREF(cause);
1964 }
1965 }
1966 print_exception(f, value);
1967 if (err != 0)
1968 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001969}
1970
Thomas Wouters477c8d52006-05-27 19:21:47 +00001971void
1972PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 PyObject *seen;
1975 PyObject *f = PySys_GetObject("stderr");
Antoine Pitrou24201d42013-10-13 21:53:13 +02001976 if (PyExceptionInstance_Check(value)
1977 && tb != NULL && PyTraceBack_Check(tb)) {
1978 /* Put the traceback on the exception, otherwise it won't get
1979 displayed. See issue #18776. */
1980 PyObject *cur_tb = PyException_GetTraceback(value);
1981 if (cur_tb == NULL)
1982 PyException_SetTraceback(value, tb);
1983 else
1984 Py_DECREF(cur_tb);
1985 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (f == Py_None) {
1987 /* pass */
1988 }
1989 else if (f == NULL) {
1990 _PyObject_Dump(value);
1991 fprintf(stderr, "lost sys.stderr\n");
1992 }
1993 else {
1994 /* We choose to ignore seen being possibly NULL, and report
1995 at least the main exception (it could be a MemoryError).
1996 */
1997 seen = PySet_New(NULL);
1998 if (seen == NULL)
1999 PyErr_Clear();
2000 print_exception_recursive(f, value, seen);
2001 Py_XDECREF(seen);
2002 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002003}
2004
Guido van Rossum82598051997-03-05 00:20:32 +00002005PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002006PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002008{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 PyObject *ret = NULL;
2010 mod_ty mod;
2011 PyArena *arena = PyArena_New();
2012 if (arena == NULL)
2013 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
2016 if (mod != NULL)
2017 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
2018 PyArena_Free(arena);
2019 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002020}
2021
2022PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002023PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 PyObject *ret;
2027 mod_ty mod;
2028 PyArena *arena = PyArena_New();
2029 if (arena == NULL)
2030 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
2033 flags, NULL, arena);
2034 if (closeit)
2035 fclose(fp);
2036 if (mod == NULL) {
2037 PyArena_Free(arena);
2038 return NULL;
2039 }
2040 ret = run_mod(mod, filename, globals, locals, flags, arena);
2041 PyArena_Free(arena);
2042 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002043}
2044
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002045static void
2046flush_io(void)
2047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 PyObject *f, *r;
2049 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002050 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 /* Save the current exception */
2053 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 f = PySys_GetObject("stderr");
2056 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002057 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 if (r)
2059 Py_DECREF(r);
2060 else
2061 PyErr_Clear();
2062 }
2063 f = PySys_GetObject("stdout");
2064 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002065 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 if (r)
2067 Py_DECREF(r);
2068 else
2069 PyErr_Clear();
2070 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002073}
2074
Guido van Rossum82598051997-03-05 00:20:32 +00002075static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002076run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 PyCodeObject *co;
2080 PyObject *v;
2081 co = PyAST_Compile(mod, filename, flags, arena);
2082 if (co == NULL)
2083 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002084 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 Py_DECREF(co);
2086 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002087}
2088
Guido van Rossum82598051997-03-05 00:20:32 +00002089static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002090run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 PyCodeObject *co;
2094 PyObject *v;
2095 long magic;
2096 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002097
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 magic = PyMarshal_ReadLongFromFile(fp);
2099 if (magic != PyImport_GetMagicNumber()) {
2100 PyErr_SetString(PyExc_RuntimeError,
2101 "Bad magic number in .pyc file");
2102 return NULL;
2103 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002104 /* Skip mtime and size */
2105 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002106 (void) PyMarshal_ReadLongFromFile(fp);
2107 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 if (v == NULL || !PyCode_Check(v)) {
2109 Py_XDECREF(v);
2110 PyErr_SetString(PyExc_RuntimeError,
2111 "Bad code object in .pyc file");
2112 return NULL;
2113 }
2114 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002115 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 if (v && flags)
2117 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2118 Py_DECREF(co);
2119 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002120}
2121
Guido van Rossum82598051997-03-05 00:20:32 +00002122PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002123Py_CompileStringObject(const char *str, PyObject *filename, int start,
2124 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 PyCodeObject *co;
2127 mod_ty mod;
2128 PyArena *arena = PyArena_New();
2129 if (arena == NULL)
2130 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002131
Victor Stinner14e461d2013-08-26 22:28:21 +02002132 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 if (mod == NULL) {
2134 PyArena_Free(arena);
2135 return NULL;
2136 }
2137 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2138 PyObject *result = PyAST_mod2obj(mod);
2139 PyArena_Free(arena);
2140 return result;
2141 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002142 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 PyArena_Free(arena);
2144 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002145}
2146
Victor Stinner14e461d2013-08-26 22:28:21 +02002147PyObject *
2148Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2149 PyCompilerFlags *flags, int optimize)
2150{
2151 PyObject *filename, *co;
2152 filename = PyUnicode_DecodeFSDefault(filename_str);
2153 if (filename == NULL)
2154 return NULL;
2155 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2156 Py_DECREF(filename);
2157 return co;
2158}
2159
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002160/* For use in Py_LIMITED_API */
2161#undef Py_CompileString
2162PyObject *
2163PyCompileString(const char *str, const char *filename, int start)
2164{
2165 return Py_CompileStringFlags(str, filename, start, NULL);
2166}
2167
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002168struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002169Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 struct symtable *st;
2172 mod_ty mod;
2173 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002174 PyArena *arena;
2175
2176 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 if (arena == NULL)
2178 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002181 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (mod == NULL) {
2183 PyArena_Free(arena);
2184 return NULL;
2185 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002186 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 PyArena_Free(arena);
2188 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002189}
2190
Victor Stinner14e461d2013-08-26 22:28:21 +02002191struct symtable *
2192Py_SymtableString(const char *str, const char *filename_str, int start)
2193{
2194 PyObject *filename;
2195 struct symtable *st;
2196
2197 filename = PyUnicode_DecodeFSDefault(filename_str);
2198 if (filename == NULL)
2199 return NULL;
2200 st = Py_SymtableStringObject(str, filename, start);
2201 Py_DECREF(filename);
2202 return st;
2203}
2204
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002205/* Preferred access to parser is through AST. */
2206mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002207PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2208 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 mod_ty mod;
2211 PyCompilerFlags localflags;
2212 perrdetail err;
2213 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002214
Victor Stinner14e461d2013-08-26 22:28:21 +02002215 node *n = PyParser_ParseStringObject(s, filename,
2216 &_PyParser_Grammar, start, &err,
2217 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 if (flags == NULL) {
2219 localflags.cf_flags = 0;
2220 flags = &localflags;
2221 }
2222 if (n) {
2223 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002224 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 }
2227 else {
2228 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002229 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002231 err_free(&err);
2232 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002233}
2234
2235mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002236PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2237 PyCompilerFlags *flags, PyArena *arena)
2238{
2239 PyObject *filename;
2240 mod_ty mod;
2241 filename = PyUnicode_DecodeFSDefault(filename_str);
2242 if (filename == NULL)
2243 return NULL;
2244 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2245 Py_DECREF(filename);
2246 return mod;
2247}
2248
2249mod_ty
2250PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2251 int start, char *ps1,
2252 char *ps2, PyCompilerFlags *flags, int *errcode,
2253 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 mod_ty mod;
2256 PyCompilerFlags localflags;
2257 perrdetail err;
2258 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002259
Victor Stinner14e461d2013-08-26 22:28:21 +02002260 node *n = PyParser_ParseFileObject(fp, filename, enc,
2261 &_PyParser_Grammar,
2262 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 if (flags == NULL) {
2264 localflags.cf_flags = 0;
2265 flags = &localflags;
2266 }
2267 if (n) {
2268 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002269 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002270 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 }
2272 else {
2273 err_input(&err);
2274 if (errcode)
2275 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002276 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002278 err_free(&err);
2279 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002280}
2281
Victor Stinner14e461d2013-08-26 22:28:21 +02002282mod_ty
2283PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2284 int start, char *ps1,
2285 char *ps2, PyCompilerFlags *flags, int *errcode,
2286 PyArena *arena)
2287{
2288 mod_ty mod;
2289 PyObject *filename;
2290 filename = PyUnicode_DecodeFSDefault(filename_str);
2291 if (filename == NULL)
2292 return NULL;
2293 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2294 flags, errcode, arena);
2295 Py_DECREF(filename);
2296 return mod;
2297}
2298
Guido van Rossuma110aa61994-08-29 12:50:44 +00002299/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002300
Guido van Rossuma110aa61994-08-29 12:50:44 +00002301node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002302PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 perrdetail err;
2305 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2306 &_PyParser_Grammar,
2307 start, NULL, NULL, &err, flags);
2308 if (n == NULL)
2309 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002310 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002313}
2314
Guido van Rossuma110aa61994-08-29 12:50:44 +00002315/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002316
Guido van Rossuma110aa61994-08-29 12:50:44 +00002317node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002318PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 perrdetail err;
2321 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2322 start, &err, flags);
2323 if (n == NULL)
2324 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002325 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002327}
2328
2329node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002330PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 perrdetail err;
2334 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2335 &_PyParser_Grammar, start, &err, flags);
2336 if (n == NULL)
2337 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002338 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002340}
2341
2342node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002343PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002344{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002346}
2347
Guido van Rossum66ebd912003-04-17 16:02:26 +00002348/* May want to move a more generalized form of this to parsetok.c or
2349 even parser modules. */
2350
2351void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002352PyParser_ClearError(perrdetail *err)
2353{
2354 err_free(err);
2355}
2356
2357void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002358PyParser_SetError(perrdetail *err)
2359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002361}
2362
Victor Stinner7f2fee32011-04-05 00:39:01 +02002363static void
2364err_free(perrdetail *err)
2365{
2366 Py_CLEAR(err->filename);
2367}
2368
Guido van Rossuma110aa61994-08-29 12:50:44 +00002369/* Set the error appropriate to the given input error code (see errcode.h) */
2370
2371static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002372err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 PyObject *v, *w, *errtype, *errtext;
2375 PyObject *msg_obj = NULL;
2376 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 errtype = PyExc_SyntaxError;
2379 switch (err->error) {
2380 case E_ERROR:
2381 return;
2382 case E_SYNTAX:
2383 errtype = PyExc_IndentationError;
2384 if (err->expected == INDENT)
2385 msg = "expected an indented block";
2386 else if (err->token == INDENT)
2387 msg = "unexpected indent";
2388 else if (err->token == DEDENT)
2389 msg = "unexpected unindent";
2390 else {
2391 errtype = PyExc_SyntaxError;
2392 msg = "invalid syntax";
2393 }
2394 break;
2395 case E_TOKEN:
2396 msg = "invalid token";
2397 break;
2398 case E_EOFS:
2399 msg = "EOF while scanning triple-quoted string literal";
2400 break;
2401 case E_EOLS:
2402 msg = "EOL while scanning string literal";
2403 break;
2404 case E_INTR:
2405 if (!PyErr_Occurred())
2406 PyErr_SetNone(PyExc_KeyboardInterrupt);
2407 goto cleanup;
2408 case E_NOMEM:
2409 PyErr_NoMemory();
2410 goto cleanup;
2411 case E_EOF:
2412 msg = "unexpected EOF while parsing";
2413 break;
2414 case E_TABSPACE:
2415 errtype = PyExc_TabError;
2416 msg = "inconsistent use of tabs and spaces in indentation";
2417 break;
2418 case E_OVERFLOW:
2419 msg = "expression too long";
2420 break;
2421 case E_DEDENT:
2422 errtype = PyExc_IndentationError;
2423 msg = "unindent does not match any outer indentation level";
2424 break;
2425 case E_TOODEEP:
2426 errtype = PyExc_IndentationError;
2427 msg = "too many levels of indentation";
2428 break;
2429 case E_DECODE: {
2430 PyObject *type, *value, *tb;
2431 PyErr_Fetch(&type, &value, &tb);
2432 msg = "unknown decode error";
2433 if (value != NULL)
2434 msg_obj = PyObject_Str(value);
2435 Py_XDECREF(type);
2436 Py_XDECREF(value);
2437 Py_XDECREF(tb);
2438 break;
2439 }
2440 case E_LINECONT:
2441 msg = "unexpected character after line continuation character";
2442 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 case E_IDENTIFIER:
2445 msg = "invalid character in identifier";
2446 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002447 case E_BADSINGLE:
2448 msg = "multiple statements found while compiling a single statement";
2449 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 default:
2451 fprintf(stderr, "error=%d\n", err->error);
2452 msg = "unknown parsing error";
2453 break;
2454 }
2455 /* err->text may not be UTF-8 in case of decoding errors.
2456 Explicitly convert to an object. */
2457 if (!err->text) {
2458 errtext = Py_None;
2459 Py_INCREF(Py_None);
2460 } else {
2461 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2462 "replace");
2463 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002464 v = Py_BuildValue("(OiiN)", err->filename,
2465 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 if (v != NULL) {
2467 if (msg_obj)
2468 w = Py_BuildValue("(OO)", msg_obj, v);
2469 else
2470 w = Py_BuildValue("(sO)", msg, v);
2471 } else
2472 w = NULL;
2473 Py_XDECREF(v);
2474 PyErr_SetObject(errtype, w);
2475 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002476cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 Py_XDECREF(msg_obj);
2478 if (err->text != NULL) {
2479 PyObject_FREE(err->text);
2480 err->text = NULL;
2481 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002482}
2483
2484/* Print fatal error message and abort */
2485
2486void
Tim Peters7c321a82002-07-09 02:57:01 +00002487Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002488{
Victor Stinner024e37a2011-03-31 01:31:06 +02002489 const int fd = fileno(stderr);
2490 PyThreadState *tstate;
2491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 fprintf(stderr, "Fatal Python error: %s\n", msg);
2493 fflush(stderr); /* it helps in Windows debug build */
2494 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002495 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002497 else {
2498 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2499 if (tstate != NULL) {
2500 fputc('\n', stderr);
2501 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002502 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002503 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002504 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002505 }
2506
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002507#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 {
2509 size_t len = strlen(msg);
2510 WCHAR* buffer;
2511 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 /* Convert the message to wchar_t. This uses a simple one-to-one
2514 conversion, assuming that the this error message actually uses ASCII
2515 only. If this ceases to be true, we will have to convert. */
2516 buffer = alloca( (len+1) * (sizeof *buffer));
2517 for( i=0; i<=len; ++i)
2518 buffer[i] = msg[i];
2519 OutputDebugStringW(L"Fatal Python error: ");
2520 OutputDebugStringW(buffer);
2521 OutputDebugStringW(L"\n");
2522 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002523#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002525#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002526#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002528}
2529
2530/* Clean up and exit */
2531
Guido van Rossuma110aa61994-08-29 12:50:44 +00002532#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002533#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002534#endif
2535
Collin Winter670e6922007-03-21 02:57:17 +00002536static void (*pyexitfunc)(void) = NULL;
2537/* For the atexit module. */
2538void _Py_PyAtExit(void (*func)(void))
2539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002541}
2542
2543static void
2544call_py_exitfuncs(void)
2545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 if (pyexitfunc == NULL)
2547 return;
Collin Winter670e6922007-03-21 02:57:17 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 (*pyexitfunc)();
2550 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002551}
2552
Antoine Pitrou011bd622009-10-20 21:52:47 +00002553/* Wait until threading._shutdown completes, provided
2554 the threading module was imported in the first place.
2555 The shutdown routine will wait until all non-daemon
2556 "threading" threads have completed. */
2557static void
2558wait_for_thread_shutdown(void)
2559{
2560#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002561 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 PyObject *result;
2563 PyThreadState *tstate = PyThreadState_GET();
2564 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2565 "threading");
2566 if (threading == NULL) {
2567 /* threading not imported */
2568 PyErr_Clear();
2569 return;
2570 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002571 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 if (result == NULL) {
2573 PyErr_WriteUnraisable(threading);
2574 }
2575 else {
2576 Py_DECREF(result);
2577 }
2578 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002579#endif
2580}
2581
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002582#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002583static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002584static int nexitfuncs = 0;
2585
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002586int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002588 if (nexitfuncs >= NEXITFUNCS)
2589 return -1;
2590 exitfuncs[nexitfuncs++] = func;
2591 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002592}
2593
Guido van Rossumcc283f51997-08-05 02:22:03 +00002594static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002595call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 while (nexitfuncs > 0)
2598 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 fflush(stdout);
2601 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002602}
2603
2604void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002605Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002610}
2611
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002612static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002613initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002614{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002615#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002617#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002618#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002620#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002621#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002623#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002625 if (PyErr_Occurred()) {
2626 Py_FatalError("Py_Initialize: can't import signal");
2627 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002628}
2629
Guido van Rossum7433b121997-02-14 19:45:36 +00002630
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002631/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2632 *
2633 * All of the code in this function must only use async-signal-safe functions,
2634 * listed at `man 7 signal` or
2635 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2636 */
2637void
2638_Py_RestoreSignals(void)
2639{
2640#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002642#endif
2643#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002645#endif
2646#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002648#endif
2649}
2650
2651
Guido van Rossum7433b121997-02-14 19:45:36 +00002652/*
2653 * The file descriptor fd is considered ``interactive'' if either
2654 * a) isatty(fd) is TRUE, or
2655 * b) the -i flag was given, and the filename associated with
2656 * the descriptor is NULL or "<stdin>" or "???".
2657 */
2658int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002659Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 if (isatty((int)fileno(fp)))
2662 return 1;
2663 if (!Py_InteractiveFlag)
2664 return 0;
2665 return (filename == NULL) ||
2666 (strcmp(filename, "<stdin>") == 0) ||
2667 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002668}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002669
2670
Tim Petersd08e3822003-04-17 15:24:21 +00002671#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002672#if defined(WIN32) && defined(_MSC_VER)
2673
2674/* Stack checking for Microsoft C */
2675
2676#include <malloc.h>
2677#include <excpt.h>
2678
Fred Drakee8de31c2000-08-31 05:38:39 +00002679/*
2680 * Return non-zero when we run out of memory on the stack; zero otherwise.
2681 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002682int
Fred Drake399739f2000-08-31 05:52:44 +00002683PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 __try {
2686 /* alloca throws a stack overflow exception if there's
2687 not enough space left on the stack */
2688 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2689 return 0;
2690 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2691 EXCEPTION_EXECUTE_HANDLER :
2692 EXCEPTION_CONTINUE_SEARCH) {
2693 int errcode = _resetstkoflw();
2694 if (errcode == 0)
2695 {
2696 Py_FatalError("Could not reset the stack!");
2697 }
2698 }
2699 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002700}
2701
2702#endif /* WIN32 && _MSC_VER */
2703
2704/* Alternate implementations can be added here... */
2705
2706#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002707
2708
2709/* Wrappers around sigaction() or signal(). */
2710
2711PyOS_sighandler_t
2712PyOS_getsig(int sig)
2713{
2714#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 struct sigaction context;
2716 if (sigaction(sig, NULL, &context) == -1)
2717 return SIG_ERR;
2718 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002719#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002721/* Special signal handling for the secure CRT in Visual Studio 2005 */
2722#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 switch (sig) {
2724 /* Only these signals are valid */
2725 case SIGINT:
2726 case SIGILL:
2727 case SIGFPE:
2728 case SIGSEGV:
2729 case SIGTERM:
2730 case SIGBREAK:
2731 case SIGABRT:
2732 break;
2733 /* Don't call signal() with other values or it will assert */
2734 default:
2735 return SIG_ERR;
2736 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002737#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002738 handler = signal(sig, SIG_IGN);
2739 if (handler != SIG_ERR)
2740 signal(sig, handler);
2741 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002742#endif
2743}
2744
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002745/*
2746 * All of the code in this function must only use async-signal-safe functions,
2747 * listed at `man 7 signal` or
2748 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2749 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002750PyOS_sighandler_t
2751PyOS_setsig(int sig, PyOS_sighandler_t handler)
2752{
2753#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 /* Some code in Modules/signalmodule.c depends on sigaction() being
2755 * used here if HAVE_SIGACTION is defined. Fix that if this code
2756 * changes to invalidate that assumption.
2757 */
2758 struct sigaction context, ocontext;
2759 context.sa_handler = handler;
2760 sigemptyset(&context.sa_mask);
2761 context.sa_flags = 0;
2762 if (sigaction(sig, &context, &ocontext) == -1)
2763 return SIG_ERR;
2764 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002765#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 PyOS_sighandler_t oldhandler;
2767 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002768#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002770#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002772#endif
2773}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774
2775/* Deprecated C API functions still provided for binary compatiblity */
2776
2777#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002778PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002779PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002782}
2783
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002784#undef PyParser_SimpleParseString
2785PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002786PyParser_SimpleParseString(const char *str, int start)
2787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002789}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002790
2791#undef PyRun_AnyFile
2792PyAPI_FUNC(int)
2793PyRun_AnyFile(FILE *fp, const char *name)
2794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002796}
2797
2798#undef PyRun_AnyFileEx
2799PyAPI_FUNC(int)
2800PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002803}
2804
2805#undef PyRun_AnyFileFlags
2806PyAPI_FUNC(int)
2807PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002810}
2811
2812#undef PyRun_File
2813PyAPI_FUNC(PyObject *)
2814PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002817}
2818
2819#undef PyRun_FileEx
2820PyAPI_FUNC(PyObject *)
2821PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002824}
2825
2826#undef PyRun_FileFlags
2827PyAPI_FUNC(PyObject *)
2828PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002829 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002832}
2833
2834#undef PyRun_SimpleFile
2835PyAPI_FUNC(int)
2836PyRun_SimpleFile(FILE *f, const char *p)
2837{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002839}
2840
2841#undef PyRun_SimpleFileEx
2842PyAPI_FUNC(int)
2843PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002846}
2847
2848
2849#undef PyRun_String
2850PyAPI_FUNC(PyObject *)
2851PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002854}
2855
2856#undef PyRun_SimpleString
2857PyAPI_FUNC(int)
2858PyRun_SimpleString(const char *s)
2859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002860 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002861}
2862
2863#undef Py_CompileString
2864PyAPI_FUNC(PyObject *)
2865Py_CompileString(const char *str, const char *p, int s)
2866{
Georg Brandl8334fd92010-12-04 10:26:46 +00002867 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2868}
2869
2870#undef Py_CompileStringFlags
2871PyAPI_FUNC(PyObject *)
2872Py_CompileStringFlags(const char *str, const char *p, int s,
2873 PyCompilerFlags *flags)
2874{
2875 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002876}
2877
2878#undef PyRun_InteractiveOne
2879PyAPI_FUNC(int)
2880PyRun_InteractiveOne(FILE *f, const char *p)
2881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002883}
2884
2885#undef PyRun_InteractiveLoop
2886PyAPI_FUNC(int)
2887PyRun_InteractiveLoop(FILE *f, const char *p)
2888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002890}
2891
2892#ifdef __cplusplus
2893}
2894#endif