blob: 3bcc4742d1ed695156d24e4160be2861660844d8 [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 }
151 if (encoding) {
152 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
153 if (!_Py_StandardStreamEncoding) {
154 PyErr_NoMemory();
155 return -1;
156 }
157 }
158 if (errors) {
159 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
160 if (!_Py_StandardStreamErrors) {
161 if (_Py_StandardStreamEncoding) {
162 PyMem_RawFree(_Py_StandardStreamEncoding);
163 }
164 PyErr_NoMemory();
165 return -1;
166 }
167 }
168 return 0;
169}
170
Guido van Rossum25ce5661997-08-02 03:10:38 +0000171/* Global initializations. Can be undone by Py_Finalize(). Don't
172 call this twice without an intervening Py_Finalize() call. When
173 initializations fail, a fatal error is issued and the function does
174 not return. On return, the first thread and interpreter state have
175 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000176
Guido van Rossum25ce5661997-08-02 03:10:38 +0000177 Locking: you must hold the interpreter lock while calling this.
178 (If the lock has not yet been initialized, that's equivalent to
179 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000180
Guido van Rossum25ce5661997-08-02 03:10:38 +0000181*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000182
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000183static int
184add_flag(int flag, const char *envs)
185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 int env = atoi(envs);
187 if (flag < env)
188 flag = env;
189 if (flag < 1)
190 flag = 1;
191 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000192}
193
Christian Heimes5833a2f2008-10-30 21:40:04 +0000194static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000195get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000196{
Victor Stinner94908bb2010-08-18 21:23:25 +0000197 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000198 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200199 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000200
Victor Stinner94908bb2010-08-18 21:23:25 +0000201 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 if (!codec)
203 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000204
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200205 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 Py_CLEAR(codec);
207 if (!name)
208 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000209
Victor Stinner94908bb2010-08-18 21:23:25 +0000210 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100211 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000212 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200213 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000215 if (name_str == NULL) {
216 PyErr_NoMemory();
217 return NULL;
218 }
219 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000220
221error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000223 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000225}
Victor Stinner94908bb2010-08-18 21:23:25 +0000226
Victor Stinner94908bb2010-08-18 21:23:25 +0000227static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200228get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000229{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200230#ifdef MS_WINDOWS
231 char codepage[100];
232 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
233 return get_codec_name(codepage);
234#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000235 char* codeset = nl_langinfo(CODESET);
236 if (!codeset || codeset[0] == '\0') {
237 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
238 return NULL;
239 }
240 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200241#else
242 PyErr_SetNone(PyExc_NotImplementedError);
243 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000244#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200245}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000246
Brett Cannonfd074152012-04-14 14:10:13 -0400247static void
248import_init(PyInterpreterState *interp, PyObject *sysmod)
249{
250 PyObject *importlib;
251 PyObject *impmod;
252 PyObject *sys_modules;
253 PyObject *value;
254
255 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400256 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
257 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
258 }
259 else if (Py_VerboseFlag) {
260 PySys_FormatStderr("import _frozen_importlib # frozen\n");
261 }
262 importlib = PyImport_AddModule("_frozen_importlib");
263 if (importlib == NULL) {
264 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
265 "sys.modules");
266 }
267 interp->importlib = importlib;
268 Py_INCREF(interp->importlib);
269
270 /* Install _importlib as __import__ */
271 impmod = PyInit_imp();
272 if (impmod == NULL) {
273 Py_FatalError("Py_Initialize: can't import imp");
274 }
275 else if (Py_VerboseFlag) {
276 PySys_FormatStderr("import imp # builtin\n");
277 }
278 sys_modules = PyImport_GetModuleDict();
279 if (Py_VerboseFlag) {
280 PySys_FormatStderr("import sys # builtin\n");
281 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400282 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
283 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400284 }
285
Brett Cannone0d88a12012-04-25 20:54:04 -0400286 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400287 if (value == NULL) {
288 PyErr_Print();
289 Py_FatalError("Py_Initialize: importlib install failed");
290 }
291 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400292 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400293
294 _PyImportZip_Init();
295}
296
297
Guido van Rossuma027efa1997-05-05 20:56:21 +0000298void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200299_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 PyInterpreterState *interp;
302 PyThreadState *tstate;
303 PyObject *bimod, *sysmod, *pstderr;
304 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 if (initialized)
308 return;
309 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200310 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000311
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000312#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 /* Set up the LC_CTYPE locale, so we can obtain
314 the locale's charset without having to switch
315 locales. */
316 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000317#endif
318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
320 Py_DebugFlag = add_flag(Py_DebugFlag, p);
321 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
322 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
323 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
324 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
325 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
326 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100327 /* The variable is only tested for existence here; _PyRandom_Init will
328 check its value further. */
329 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
330 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
331
332 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 interp = PyInterpreterState_New();
335 if (interp == NULL)
336 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 tstate = PyThreadState_New(interp);
339 if (tstate == NULL)
340 Py_FatalError("Py_Initialize: can't make first thread");
341 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000342
Victor Stinner6961bd62010-08-17 22:26:51 +0000343#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000344 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
345 destroying the GIL might fail when it is being referenced from
346 another running thread (see issue #9901).
347 Instead we destroy the previously created GIL here, which ensures
348 that we can call Py_Initialize / Py_Finalize multiple times. */
349 _PyEval_FiniThreads();
350
351 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000352 _PyGILState_Init(interp, tstate);
353#endif /* WITH_THREAD */
354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 if (!_PyFrame_Init())
358 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 if (!_PyLong_Init())
361 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 if (!PyByteArray_Init())
364 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000365
Victor Stinner1c8f0592013-07-22 22:24:54 +0200366 if (!_PyFloat_Init())
367 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 interp->modules = PyDict_New();
370 if (interp->modules == NULL)
371 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200374 if (_PyUnicode_Init() < 0)
375 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200376 if (_PyStructSequence_Init() < 0)
377 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 bimod = _PyBuiltin_Init();
380 if (bimod == NULL)
381 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000382 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 interp->builtins = PyModule_GetDict(bimod);
384 if (interp->builtins == NULL)
385 Py_FatalError("Py_Initialize: can't initialize builtins dict");
386 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400389 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 sysmod = _PySys_Init();
392 if (sysmod == NULL)
393 Py_FatalError("Py_Initialize: can't initialize sys");
394 interp->sysdict = PyModule_GetDict(sysmod);
395 if (interp->sysdict == NULL)
396 Py_FatalError("Py_Initialize: can't initialize sys dict");
397 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000398 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 PySys_SetPath(Py_GetPath());
400 PyDict_SetItemString(interp->sysdict, "modules",
401 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 /* Set up a preliminary stderr printer until we have enough
404 infrastructure for the io module in place. */
405 pstderr = PyFile_NewStdPrinter(fileno(stderr));
406 if (pstderr == NULL)
407 Py_FatalError("Py_Initialize: can't set preliminary stderr");
408 PySys_SetObject("stderr", pstderr);
409 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000410 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000415
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000416 /* Initialize _warnings. */
417 _PyWarnings_Init();
418
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200419 if (!install_importlib)
420 return;
421
Brett Cannonfd074152012-04-14 14:10:13 -0400422 import_init(interp, sysmod);
423
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200424 /* initialize the faulthandler module */
425 if (_PyFaulthandler_Init())
426 Py_FatalError("Py_Initialize: can't initialize faulthandler");
427
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000428 _PyTime_Init();
429
Victor Stinner793b5312011-04-27 00:24:21 +0200430 if (initfsencoding(interp) < 0)
431 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 if (install_sigs)
434 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000435
Nick Coghlan85e729e2012-07-15 18:09:52 +1000436 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (initstdio() < 0)
438 Py_FatalError(
439 "Py_Initialize: can't initialize sys standard streams");
440
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000441 /* Initialize warnings. */
442 if (PySys_HasWarnOptions()) {
443 PyObject *warnings_module = PyImport_ImportModule("warnings");
444 if (warnings_module == NULL) {
445 fprintf(stderr, "'import warnings' failed; traceback:\n");
446 PyErr_Print();
447 }
448 Py_XDECREF(warnings_module);
449 }
450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (!Py_NoSiteFlag)
452 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000453}
454
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000455void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200456Py_InitializeEx(int install_sigs)
457{
458 _Py_InitializeEx_Private(install_sigs, 1);
459}
460
461void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000462Py_Initialize(void)
463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000465}
466
467
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000468#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000469extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000470#endif
471
Guido van Rossume8432ac2007-07-09 15:04:50 +0000472/* Flush stdout and stderr */
473
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100474static int
475file_is_closed(PyObject *fobj)
476{
477 int r;
478 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
479 if (tmp == NULL) {
480 PyErr_Clear();
481 return 0;
482 }
483 r = PyObject_IsTrue(tmp);
484 Py_DECREF(tmp);
485 if (r < 0)
486 PyErr_Clear();
487 return r > 0;
488}
489
Neal Norwitz2bad9702007-08-27 06:19:22 +0000490static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000491flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 PyObject *fout = PySys_GetObject("stdout");
494 PyObject *ferr = PySys_GetObject("stderr");
495 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200496 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000497
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100498 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200499 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000501 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 else
503 Py_DECREF(tmp);
504 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000505
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100506 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200507 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 if (tmp == NULL)
509 PyErr_Clear();
510 else
511 Py_DECREF(tmp);
512 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000513}
514
Guido van Rossum25ce5661997-08-02 03:10:38 +0000515/* Undo the effect of Py_Initialize().
516
517 Beware: if multiple interpreter and/or thread states exist, these
518 are not wiped out; only the current thread and interpreter state
519 are deleted. But since everything else is deleted, those other
520 interpreter and thread states should no longer be used.
521
522 (XXX We should do better, e.g. wipe out all interpreters and
523 threads.)
524
525 Locking: as above.
526
527*/
528
529void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000530Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 PyInterpreterState *interp;
533 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (!initialized)
536 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 /* The interpreter is still entirely intact at this point, and the
541 * exit funcs may be relying on that. In particular, if some thread
542 * or exit func is still waiting to do an import, the import machinery
543 * expects Py_IsInitialized() to return true. So don't say the
544 * interpreter is uninitialized until after the exit funcs have run.
545 * Note that Threading.py uses an exit func to do a join on all the
546 * threads created thru it, so this also protects pending imports in
547 * the threads created via Threading.
548 */
549 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 /* Get current thread state and interpreter pointer */
552 tstate = PyThreadState_GET();
553 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000554
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200555 /* Remaining threads (e.g. daemon threads) will automatically exit
556 after taking the GIL (in PyEval_RestoreThread()). */
557 _Py_Finalizing = tstate;
558 initialized = 0;
559
560 /* Flush stdout+stderr */
561 flush_std_files();
562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 /* Disable signal handling */
564 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 /* Collect garbage. This may call finalizers; it's nice to call these
567 * before all modules are destroyed.
568 * XXX If a __del__ or weakref callback is triggered here, and tries to
569 * XXX import a module, bad things can happen, because Python no
570 * XXX longer believes it's initialized.
571 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
572 * XXX is easy to provoke that way. I've also seen, e.g.,
573 * XXX Exception exceptions.ImportError: 'No module named sha'
574 * XXX in <function callback at 0x008F5718> ignored
575 * XXX but I'm unclear on exactly how that one happens. In any case,
576 * XXX I haven't seen a real-life report of either of these.
577 */
578 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000579#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 /* With COUNT_ALLOCS, it helps to run GC multiple times:
581 each collection might release some types from the type
582 list, so they become garbage. */
583 while (PyGC_Collect() > 0)
584 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000585#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 /* Destroy all modules */
587 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 /* Flush stdout+stderr (again, in case more was printed) */
590 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100593 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 * XXX This is disabled because it caused too many problems. If
595 * XXX a __del__ or weakref callback triggers here, Python code has
596 * XXX a hard time running, because even the sys module has been
597 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
598 * XXX One symptom is a sequence of information-free messages
599 * XXX coming from threads (if a __del__ or callback is invoked,
600 * XXX other threads can execute too, and any exception they encounter
601 * XXX triggers a comedy of errors as subsystem after subsystem
602 * XXX fails to find what it *expects* to find in sys to help report
603 * XXX the exception and consequent unexpected failures). I've also
604 * XXX seen segfaults then, after adding print statements to the
605 * XXX Python code getting called.
606 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000607#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000609#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
612 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000613
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200614 /* Cleanup typeobject.c's internal caches. */
615 _PyType_Fini();
616
Victor Stinner024e37a2011-03-31 01:31:06 +0200617 /* unload faulthandler module */
618 _PyFaulthandler_Fini();
619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000621#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000623#endif
624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000626
Tim Peters9cf25ce2003-04-17 15:21:01 +0000627#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 /* Display all objects still alive -- this can invoke arbitrary
629 * __repr__ overrides, so requires a mostly-intact interpreter.
630 * Alas, a lot of stuff may still be alive now that will be cleaned
631 * up later.
632 */
633 if (Py_GETENV("PYTHONDUMPREFS"))
634 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000635#endif /* Py_TRACE_REFS */
636
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200637 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 /* Now we decref the exception classes. After this point nothing
641 can raise an exception. That's okay, because each Fini() method
642 below has been checked to make sure no exceptions are ever
643 raised.
644 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 /* Sundry finalizers */
649 PyMethod_Fini();
650 PyFrame_Fini();
651 PyCFunction_Fini();
652 PyTuple_Fini();
653 PyList_Fini();
654 PySet_Fini();
655 PyBytes_Fini();
656 PyByteArray_Fini();
657 PyLong_Fini();
658 PyFloat_Fini();
659 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100660 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200661 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200662 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 /* Cleanup Unicode implementation */
665 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000668 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200669 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 Py_FileSystemDefaultEncoding = NULL;
671 }
Christian Heimesc8967002007-11-30 10:18:26 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 /* XXX Still allocated:
674 - various static ad-hoc pointers to interned strings
675 - int and float free list blocks
676 - whatever various modules and libraries allocate
677 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000680
Victor Stinner51fa4582013-07-07 15:50:49 +0200681 /* Cleanup auto-thread-state */
682#ifdef WITH_THREAD
683 _PyGILState_Fini();
684#endif /* WITH_THREAD */
685
686 /* Delete current thread. After this, many C API calls become crashy. */
687 PyThreadState_Swap(NULL);
688 PyInterpreterState_Delete(interp);
689
Tim Peters269b2a62003-04-17 19:52:29 +0000690#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 /* Display addresses (& refcnts) of all objects still alive.
692 * An address can be used to find the repr of the object, printed
693 * above by _Py_PrintReferences.
694 */
695 if (Py_GETENV("PYTHONDUMPREFS"))
696 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000697#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000698#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400700 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000701#endif
702
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000704}
705
706/* Create and initialize a new interpreter and thread, and return the
707 new thread. This requires that Py_Initialize() has been called
708 first.
709
710 Unsuccessful initialization yields a NULL pointer. Note that *no*
711 exception information is available even in this case -- the
712 exception information is held in the thread, and there is no
713 thread.
714
715 Locking: as above.
716
717*/
718
719PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000720Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000721{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 PyInterpreterState *interp;
723 PyThreadState *tstate, *save_tstate;
724 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (!initialized)
727 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 interp = PyInterpreterState_New();
730 if (interp == NULL)
731 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 tstate = PyThreadState_New(interp);
734 if (tstate == NULL) {
735 PyInterpreterState_Delete(interp);
736 return NULL;
737 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000744
Victor Stinner49d3f252010-10-17 01:24:53 +0000745 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (bimod != NULL) {
747 interp->builtins = PyModule_GetDict(bimod);
748 if (interp->builtins == NULL)
749 goto handle_error;
750 Py_INCREF(interp->builtins);
751 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400754 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000755
Victor Stinner49d3f252010-10-17 01:24:53 +0000756 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (bimod != NULL && sysmod != NULL) {
758 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 interp->sysdict = PyModule_GetDict(sysmod);
761 if (interp->sysdict == NULL)
762 goto handle_error;
763 Py_INCREF(interp->sysdict);
764 PySys_SetPath(Py_GetPath());
765 PyDict_SetItemString(interp->sysdict, "modules",
766 interp->modules);
767 /* Set up a preliminary stderr printer until we have enough
768 infrastructure for the io module in place. */
769 pstderr = PyFile_NewStdPrinter(fileno(stderr));
770 if (pstderr == NULL)
771 Py_FatalError("Py_Initialize: can't set preliminary stderr");
772 PySys_SetObject("stderr", pstderr);
773 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000774 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200777
Brett Cannonfd074152012-04-14 14:10:13 -0400778 import_init(interp, sysmod);
779
Victor Stinner793b5312011-04-27 00:24:21 +0200780 if (initfsencoding(interp) < 0)
781 goto handle_error;
782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (initstdio() < 0)
784 Py_FatalError(
785 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000786 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (!Py_NoSiteFlag)
788 initsite();
789 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (!PyErr_Occurred())
792 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000793
Thomas Wouters89f507f2006-12-13 04:49:30 +0000794handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000796
Victor Stinnerc40a3502011-04-27 00:20:27 +0200797 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 PyThreadState_Clear(tstate);
799 PyThreadState_Swap(save_tstate);
800 PyThreadState_Delete(tstate);
801 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000804}
805
806/* Delete an interpreter and its last thread. This requires that the
807 given thread state is current, that the thread has no remaining
808 frames, and that it is its interpreter's only remaining thread.
809 It is a fatal error to violate these constraints.
810
811 (Py_Finalize() doesn't have these constraints -- it zaps
812 everything, regardless.)
813
814 Locking: as above.
815
816*/
817
818void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000819Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (tstate != PyThreadState_GET())
824 Py_FatalError("Py_EndInterpreter: thread is not current");
825 if (tstate->frame != NULL)
826 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200827
828 wait_for_thread_shutdown();
829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (tstate != interp->tstate_head || tstate->next != NULL)
831 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyImport_Cleanup();
834 PyInterpreterState_Clear(interp);
835 PyThreadState_Swap(NULL);
836 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000837}
838
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200839#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000840static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200841#else
842static wchar_t *progname = L"python3";
843#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000844
845void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000846Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 if (pn && *pn)
849 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000850}
851
Martin v. Löwis790465f2008-04-05 20:41:37 +0000852wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000853Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000856}
857
Martin v. Löwis790465f2008-04-05 20:41:37 +0000858static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200859static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000860
861void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000862Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000865}
866
Martin v. Löwis790465f2008-04-05 20:41:37 +0000867wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000868Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 wchar_t *home = default_home;
871 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
872 char* chome = Py_GETENV("PYTHONHOME");
873 if (chome) {
874 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
875 if (r != (size_t)-1 && r <= PATH_MAX)
876 home = env_home;
877 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 }
880 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000881}
882
Guido van Rossum6135a871995-01-09 17:53:26 +0000883/* Create __main__ module */
884
885static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000886initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000887{
Brett Cannon13853a62013-05-04 17:37:09 -0400888 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 m = PyImport_AddModule("__main__");
890 if (m == NULL)
891 Py_FatalError("can't create __main__ module");
892 d = PyModule_GetDict(m);
893 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
894 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000895 if (bimod == NULL) {
896 Py_FatalError("Failed to retrieve builtins module");
897 }
898 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
899 Py_FatalError("Failed to initialize __main__.__builtins__");
900 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 Py_DECREF(bimod);
902 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000903 /* Main is a little special - imp.is_builtin("__main__") will return
904 * False, but BuiltinImporter is still the most appropriate initial
905 * setting for its __loader__ attribute. A more suitable value will
906 * be set if __main__ gets further initialized later in the startup
907 * process.
908 */
Brett Cannon13853a62013-05-04 17:37:09 -0400909 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400910 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000911 PyObject *loader = PyObject_GetAttrString(interp->importlib,
912 "BuiltinImporter");
913 if (loader == NULL) {
914 Py_FatalError("Failed to retrieve BuiltinImporter");
915 }
916 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
917 Py_FatalError("Failed to initialize __main__.__loader__");
918 }
919 Py_DECREF(loader);
920 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000921}
922
Victor Stinner793b5312011-04-27 00:24:21 +0200923static int
924initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000925{
926 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000927
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200928 if (Py_FileSystemDefaultEncoding == NULL)
929 {
930 Py_FileSystemDefaultEncoding = get_locale_encoding();
931 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000932 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000933
Victor Stinnere4743092010-10-19 00:05:51 +0000934 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200935 interp->fscodec_initialized = 1;
936 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000937 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000938
939 /* the encoding is mbcs, utf-8 or ascii */
940 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
941 if (!codec) {
942 /* Such error can only occurs in critical situations: no more
943 * memory, import a module of the standard library failed,
944 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200945 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000946 }
Victor Stinner793b5312011-04-27 00:24:21 +0200947 Py_DECREF(codec);
948 interp->fscodec_initialized = 1;
949 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000950}
951
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000952/* Import the site module (not into __main__ though) */
953
954static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000955initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000956{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 PyObject *m;
958 m = PyImport_ImportModule("site");
959 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200960 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 PyErr_Print();
962 Py_Finalize();
963 exit(1);
964 }
965 else {
966 Py_DECREF(m);
967 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000968}
969
Antoine Pitrou05608432009-01-09 18:53:14 +0000970static PyObject*
971create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 int fd, int write_mode, char* name,
973 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000974{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
976 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000977 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 PyObject *line_buffering;
979 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200980 _Py_IDENTIFIER(open);
981 _Py_IDENTIFIER(isatty);
982 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200983 _Py_IDENTIFIER(name);
984 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 /* stdin is always opened in buffered mode, first because it shouldn't
987 make a difference in common use cases, second because TextIOWrapper
988 depends on the presence of a read1() method which only exists on
989 buffered streams.
990 */
991 if (Py_UnbufferedStdioFlag && write_mode)
992 buffering = 0;
993 else
994 buffering = -1;
995 if (write_mode)
996 mode = "wb";
997 else
998 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200999 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1000 fd, mode, buffering,
1001 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 if (buf == NULL)
1003 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001006 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001007 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (raw == NULL)
1009 goto error;
1010 }
1011 else {
1012 raw = buf;
1013 Py_INCREF(raw);
1014 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001017 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001019 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 if (res == NULL)
1021 goto error;
1022 isatty = PyObject_IsTrue(res);
1023 Py_DECREF(res);
1024 if (isatty == -1)
1025 goto error;
1026 if (isatty || Py_UnbufferedStdioFlag)
1027 line_buffering = Py_True;
1028 else
1029 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 Py_CLEAR(raw);
1032 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001033
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001034#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001035 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1036 newlines to "\n".
1037 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1038 newline = NULL;
1039#else
1040 /* sys.stdin: split lines at "\n".
1041 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1042 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001043#endif
1044
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001045 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1046 buf, encoding, errors,
1047 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 Py_CLEAR(buf);
1049 if (stream == NULL)
1050 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 if (write_mode)
1053 mode = "w";
1054 else
1055 mode = "r";
1056 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001057 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 goto error;
1059 Py_CLEAR(text);
1060 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001061
1062error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 Py_XDECREF(buf);
1064 Py_XDECREF(stream);
1065 Py_XDECREF(text);
1066 Py_XDECREF(raw);
1067 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001068}
1069
Antoine Pitrou11942a52011-11-28 19:08:36 +01001070static int
1071is_valid_fd(int fd)
1072{
1073 int dummy_fd;
1074 if (fd < 0 || !_PyVerify_fd(fd))
1075 return 0;
1076 dummy_fd = dup(fd);
1077 if (dummy_fd < 0)
1078 return 0;
1079 close(dummy_fd);
1080 return 1;
1081}
1082
Georg Brandl1a3284e2007-12-02 09:40:06 +00001083/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001084static int
1085initstdio(void)
1086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 PyObject *iomod = NULL, *wrapper;
1088 PyObject *bimod = NULL;
1089 PyObject *m;
1090 PyObject *std = NULL;
1091 int status = 0, fd;
1092 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001093 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 /* Hack to avoid a nasty recursion issue when Python is invoked
1096 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1097 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1098 goto error;
1099 }
1100 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
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 (!(bimod = PyImport_ImportModule("builtins"))) {
1108 goto error;
1109 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (!(iomod = PyImport_ImportModule("io"))) {
1112 goto error;
1113 }
1114 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1115 goto error;
1116 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 /* Set builtins.open */
1119 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001120 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 goto error;
1122 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001123 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001124
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001125 encoding = _Py_StandardStreamEncoding;
1126 errors = _Py_StandardStreamErrors;
1127 if (!encoding || !errors) {
1128 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1129 if (pythonioencoding) {
1130 char *err;
1131 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1132 if (pythonioencoding == NULL) {
1133 PyErr_NoMemory();
1134 goto error;
1135 }
1136 err = strchr(pythonioencoding, ':');
1137 if (err) {
1138 *err = '\0';
1139 err++;
1140 if (*err && !errors) {
1141 errors = err;
1142 }
1143 }
1144 if (*pythonioencoding && !encoding) {
1145 encoding = pythonioencoding;
1146 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001147 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 /* Set sys.stdin */
1151 fd = fileno(stdin);
1152 /* Under some conditions stdin, stdout and stderr may not be connected
1153 * and fileno() may point to an invalid file descriptor. For example
1154 * GUI apps don't have valid standard streams by default.
1155 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001156 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 std = Py_None;
1158 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 }
1160 else {
1161 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1162 if (std == NULL)
1163 goto error;
1164 } /* if (fd < 0) */
1165 PySys_SetObject("__stdin__", std);
1166 PySys_SetObject("stdin", std);
1167 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 /* Set sys.stdout */
1170 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001171 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 std = Py_None;
1173 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 }
1175 else {
1176 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1177 if (std == NULL)
1178 goto error;
1179 } /* if (fd < 0) */
1180 PySys_SetObject("__stdout__", std);
1181 PySys_SetObject("stdout", std);
1182 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001183
Guido van Rossum98297ee2007-11-06 21:34:58 +00001184#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 /* Set sys.stderr, replaces the preliminary stderr */
1186 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001187 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 std = Py_None;
1189 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 }
1191 else {
1192 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1193 if (std == NULL)
1194 goto error;
1195 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 /* Same as hack above, pre-import stderr's codec to avoid recursion
1198 when import.c tries to write to stderr in verbose mode. */
1199 encoding_attr = PyObject_GetAttrString(std, "encoding");
1200 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001201 const char * std_encoding;
1202 std_encoding = _PyUnicode_AsString(encoding_attr);
1203 if (std_encoding != NULL) {
1204 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001205 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001207 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 }
1209 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001210
Victor Stinnerba308832013-07-22 23:55:19 +02001211 if (PySys_SetObject("__stderr__", std) < 0) {
1212 Py_DECREF(std);
1213 goto error;
1214 }
1215 if (PySys_SetObject("stderr", std) < 0) {
1216 Py_DECREF(std);
1217 goto error;
1218 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001220#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001223 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 status = -1;
1225 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001226
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001227 /* We won't need them anymore. */
1228 if (_Py_StandardStreamEncoding) {
1229 PyMem_RawFree(_Py_StandardStreamEncoding);
1230 _Py_StandardStreamEncoding = NULL;
1231 }
1232 if (_Py_StandardStreamErrors) {
1233 PyMem_RawFree(_Py_StandardStreamErrors);
1234 _Py_StandardStreamErrors = NULL;
1235 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001236 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 Py_XDECREF(bimod);
1238 Py_XDECREF(iomod);
1239 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001240}
1241
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001242/* Parse input from a file and execute it */
1243
1244int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001245PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (filename == NULL)
1249 filename = "???";
1250 if (Py_FdIsInteractive(fp, filename)) {
1251 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1252 if (closeit)
1253 fclose(fp);
1254 return err;
1255 }
1256 else
1257 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001258}
1259
1260int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001261PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyObject *v;
1264 int ret;
1265 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (flags == NULL) {
1268 flags = &local_flags;
1269 local_flags.cf_flags = 0;
1270 }
1271 v = PySys_GetObject("ps1");
1272 if (v == NULL) {
1273 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1274 Py_XDECREF(v);
1275 }
1276 v = PySys_GetObject("ps2");
1277 if (v == NULL) {
1278 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1279 Py_XDECREF(v);
1280 }
1281 for (;;) {
1282 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1283 PRINT_TOTAL_REFS();
1284 if (ret == E_EOF)
1285 return 0;
1286 /*
1287 if (ret == E_NOMEM)
1288 return -1;
1289 */
1290 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001291}
1292
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001293/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001294static int PARSER_FLAGS(PyCompilerFlags *flags)
1295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 int parser_flags = 0;
1297 if (!flags)
1298 return 0;
1299 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1300 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1301 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1302 parser_flags |= PyPARSE_IGNORE_COOKIE;
1303 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1304 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1305 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001306}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001307
Thomas Wouters89f507f2006-12-13 04:49:30 +00001308#if 0
1309/* Keep an example of flags with future keyword support. */
1310#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1312 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1313 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1314 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001315#endif
1316
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001317int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001318PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 PyObject *m, *d, *v, *w, *oenc = NULL;
1321 mod_ty mod;
1322 PyArena *arena;
1323 char *ps1 = "", *ps2 = "", *enc = NULL;
1324 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001325 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001328 /* Fetch encoding from sys.stdin if possible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 v = PySys_GetObject("stdin");
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001330 if (v && v != Py_None) {
1331 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1332 if (oenc)
1333 enc = _PyUnicode_AsString(oenc);
1334 if (!enc)
1335 PyErr_Clear();
1336 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 }
1338 v = PySys_GetObject("ps1");
1339 if (v != NULL) {
1340 v = PyObject_Str(v);
1341 if (v == NULL)
1342 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001343 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001345 if (ps1 == NULL) {
1346 PyErr_Clear();
1347 ps1 = "";
1348 }
1349 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 }
1351 w = PySys_GetObject("ps2");
1352 if (w != NULL) {
1353 w = PyObject_Str(w);
1354 if (w == NULL)
1355 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001356 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001358 if (ps2 == NULL) {
1359 PyErr_Clear();
1360 ps2 = "";
1361 }
1362 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 }
1364 arena = PyArena_New();
1365 if (arena == NULL) {
1366 Py_XDECREF(v);
1367 Py_XDECREF(w);
1368 Py_XDECREF(oenc);
1369 return -1;
1370 }
1371 mod = PyParser_ASTFromFile(fp, filename, enc,
1372 Py_single_input, ps1, ps2,
1373 flags, &errcode, arena);
1374 Py_XDECREF(v);
1375 Py_XDECREF(w);
1376 Py_XDECREF(oenc);
1377 if (mod == NULL) {
1378 PyArena_Free(arena);
1379 if (errcode == E_EOF) {
1380 PyErr_Clear();
1381 return E_EOF;
1382 }
1383 PyErr_Print();
1384 return -1;
1385 }
1386 m = PyImport_AddModule("__main__");
1387 if (m == NULL) {
1388 PyArena_Free(arena);
1389 return -1;
1390 }
1391 d = PyModule_GetDict(m);
1392 v = run_mod(mod, filename, d, d, flags, arena);
1393 PyArena_Free(arena);
1394 flush_io();
1395 if (v == NULL) {
1396 PyErr_Print();
1397 return -1;
1398 }
1399 Py_DECREF(v);
1400 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001401}
1402
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001403/* Check whether a file maybe a pyc file: Look at the extension,
1404 the file type, and, if we may close it, at the first few bytes. */
1405
1406static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001407maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1410 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 /* Only look into the file if we are allowed to close it, since
1413 it then should also be seekable. */
1414 if (closeit) {
1415 /* Read only two bytes of the magic. If the file was opened in
1416 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1417 be read as they are on disk. */
1418 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1419 unsigned char buf[2];
1420 /* Mess: In case of -x, the stream is NOT at its start now,
1421 and ungetc() was used to push back the first newline,
1422 which makes the current stream position formally undefined,
1423 and a x-platform nightmare.
1424 Unfortunately, we have no direct way to know whether -x
1425 was specified. So we use a terrible hack: if the current
1426 stream position is not 0, we assume -x was specified, and
1427 give up. Bug 132850 on SourceForge spells out the
1428 hopelessness of trying anything else (fseek and ftell
1429 don't work predictably x-platform for text-mode files).
1430 */
1431 int ispyc = 0;
1432 if (ftell(fp) == 0) {
1433 if (fread(buf, 1, 2, fp) == 2 &&
1434 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1435 ispyc = 1;
1436 rewind(fp);
1437 }
1438 return ispyc;
1439 }
1440 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001441}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001442
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001443static int
1444set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001445{
1446 PyInterpreterState *interp;
1447 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001448 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001449 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001450
1451 filename_obj = PyUnicode_DecodeFSDefault(filename);
1452 if (filename_obj == NULL)
1453 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001454 /* Get current thread state and interpreter pointer */
1455 tstate = PyThreadState_GET();
1456 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001457 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1458 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001459 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001460 return -1;
1461 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001462 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001463 Py_DECREF(loader_type);
1464 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001465 return -1;
1466 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001467 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1468 result = -1;
1469 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001470 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001471 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001472}
1473
1474int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001475PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 PyObject *m, *d, *v;
1479 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001480 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001481 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 m = PyImport_AddModule("__main__");
1484 if (m == NULL)
1485 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001486 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 d = PyModule_GetDict(m);
1488 if (PyDict_GetItemString(d, "__file__") == NULL) {
1489 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001490 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001492 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1494 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001495 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001497 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1498 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001499 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001500 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 set_file_name = 1;
1502 Py_DECREF(f);
1503 }
1504 len = strlen(filename);
1505 ext = filename + len - (len > 4 ? 4 : 0);
1506 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001507 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 /* Try to run a pyc file. First, re-open in binary */
1509 if (closeit)
1510 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001511 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 goto done;
1514 }
1515 /* Turn on optimization if a .pyo file is given */
1516 if (strcmp(ext, ".pyo") == 0)
1517 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001518
1519 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1520 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1521 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001522 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001523 goto done;
1524 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001525 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1526 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001528 /* When running from stdin, leave __main__.__loader__ alone */
1529 if (strcmp(filename, "<stdin>") != 0 &&
1530 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1531 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1532 ret = -1;
1533 goto done;
1534 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1536 closeit, flags);
1537 }
1538 flush_io();
1539 if (v == NULL) {
1540 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 goto done;
1542 }
1543 Py_DECREF(v);
1544 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001545 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1547 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001548 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001550}
1551
1552int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001553PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 PyObject *m, *d, *v;
1556 m = PyImport_AddModule("__main__");
1557 if (m == NULL)
1558 return -1;
1559 d = PyModule_GetDict(m);
1560 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1561 if (v == NULL) {
1562 PyErr_Print();
1563 return -1;
1564 }
1565 Py_DECREF(v);
1566 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001567}
1568
Barry Warsaw035574d1997-08-29 22:07:17 +00001569static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001570parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 long hold;
1574 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001575 _Py_IDENTIFIER(msg);
1576 _Py_IDENTIFIER(filename);
1577 _Py_IDENTIFIER(lineno);
1578 _Py_IDENTIFIER(offset);
1579 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001580
Benjamin Peterson80d50422012-04-03 00:30:38 -04001581 *message = NULL;
1582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001584 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001585 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001587
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001588 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001589 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001591 if (v == Py_None) {
1592 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001594 }
1595 else {
1596 *filename = _PyUnicode_AsString(v);
1597 Py_DECREF(v);
1598 if (!*filename)
1599 goto finally;
1600 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001601
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001602 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001603 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 goto finally;
1605 hold = PyLong_AsLong(v);
1606 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (hold < 0 && PyErr_Occurred())
1608 goto finally;
1609 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001610
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001611 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001612 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 goto finally;
1614 if (v == Py_None) {
1615 *offset = -1;
1616 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 } else {
1618 hold = PyLong_AsLong(v);
1619 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 if (hold < 0 && PyErr_Occurred())
1621 goto finally;
1622 *offset = (int)hold;
1623 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001624
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001625 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001626 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001628 if (v == Py_None) {
1629 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001631 }
1632 else {
1633 *text = _PyUnicode_AsString(v);
1634 Py_DECREF(v);
1635 if (!*text)
1636 goto finally;
1637 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001639
1640finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001641 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001643}
1644
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001645void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001646PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001649}
1650
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001651static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001652print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 char *nl;
1655 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001656 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1657 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 for (;;) {
1659 nl = strchr(text, '\n');
1660 if (nl == NULL || nl-text >= offset)
1661 break;
1662 offset -= (int)(nl+1-text);
1663 text = nl+1;
1664 }
1665 while (*text == ' ' || *text == '\t') {
1666 text++;
1667 offset--;
1668 }
1669 }
1670 PyFile_WriteString(" ", f);
1671 PyFile_WriteString(text, f);
1672 if (*text == '\0' || text[strlen(text)-1] != '\n')
1673 PyFile_WriteString("\n", f);
1674 if (offset == -1)
1675 return;
1676 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001677 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001680}
1681
Guido van Rossum66e8e862001-03-23 17:54:43 +00001682static void
1683handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyObject *exception, *value, *tb;
1686 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 if (Py_InspectFlag)
1689 /* Don't exit if -i flag was given. This flag is set to 0
1690 * when entering interactive mode for inspecting. */
1691 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 PyErr_Fetch(&exception, &value, &tb);
1694 fflush(stdout);
1695 if (value == NULL || value == Py_None)
1696 goto done;
1697 if (PyExceptionInstance_Check(value)) {
1698 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001699 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001700 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (code) {
1702 Py_DECREF(value);
1703 value = code;
1704 if (value == Py_None)
1705 goto done;
1706 }
1707 /* If we failed to dig out the 'code' attribute,
1708 just let the else clause below print the error. */
1709 }
1710 if (PyLong_Check(value))
1711 exitcode = (int)PyLong_AsLong(value);
1712 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001713 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001714 if (sys_stderr != NULL && sys_stderr != Py_None) {
1715 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1716 } else {
1717 PyObject_Print(value, stderr, Py_PRINT_RAW);
1718 fflush(stderr);
1719 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 PySys_WriteStderr("\n");
1721 exitcode = 1;
1722 }
Tim Peterscf615b52003-04-19 18:47:02 +00001723 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 /* Restore and clear the exception info, in order to properly decref
1725 * the exception, value, and traceback. If we just exit instead,
1726 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1727 * some finalizers from running.
1728 */
1729 PyErr_Restore(exception, value, tb);
1730 PyErr_Clear();
1731 Py_Exit(exitcode);
1732 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001733}
1734
1735void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001736PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001737{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1741 handle_system_exit();
1742 }
1743 PyErr_Fetch(&exception, &v, &tb);
1744 if (exception == NULL)
1745 return;
1746 PyErr_NormalizeException(&exception, &v, &tb);
1747 if (tb == NULL) {
1748 tb = Py_None;
1749 Py_INCREF(tb);
1750 }
1751 PyException_SetTraceback(v, tb);
1752 if (exception == NULL)
1753 return;
1754 /* Now we know v != NULL too */
1755 if (set_sys_last_vars) {
1756 PySys_SetObject("last_type", exception);
1757 PySys_SetObject("last_value", v);
1758 PySys_SetObject("last_traceback", tb);
1759 }
1760 hook = PySys_GetObject("excepthook");
1761 if (hook) {
1762 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1763 PyObject *result = PyEval_CallObject(hook, args);
1764 if (result == NULL) {
1765 PyObject *exception2, *v2, *tb2;
1766 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1767 handle_system_exit();
1768 }
1769 PyErr_Fetch(&exception2, &v2, &tb2);
1770 PyErr_NormalizeException(&exception2, &v2, &tb2);
1771 /* It should not be possible for exception2 or v2
1772 to be NULL. However PyErr_Display() can't
1773 tolerate NULLs, so just be safe. */
1774 if (exception2 == NULL) {
1775 exception2 = Py_None;
1776 Py_INCREF(exception2);
1777 }
1778 if (v2 == NULL) {
1779 v2 = Py_None;
1780 Py_INCREF(v2);
1781 }
1782 fflush(stdout);
1783 PySys_WriteStderr("Error in sys.excepthook:\n");
1784 PyErr_Display(exception2, v2, tb2);
1785 PySys_WriteStderr("\nOriginal exception was:\n");
1786 PyErr_Display(exception, v, tb);
1787 Py_DECREF(exception2);
1788 Py_DECREF(v2);
1789 Py_XDECREF(tb2);
1790 }
1791 Py_XDECREF(result);
1792 Py_XDECREF(args);
1793 } else {
1794 PySys_WriteStderr("sys.excepthook is missing\n");
1795 PyErr_Display(exception, v, tb);
1796 }
1797 Py_XDECREF(exception);
1798 Py_XDECREF(v);
1799 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001800}
1801
Benjamin Petersone6528212008-07-15 15:32:09 +00001802static void
1803print_exception(PyObject *f, PyObject *value)
1804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 int err = 0;
1806 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001807 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 if (!PyExceptionInstance_Check(value)) {
1810 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1811 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1812 PyFile_WriteString(" found\n", f);
1813 return;
1814 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 Py_INCREF(value);
1817 fflush(stdout);
1818 type = (PyObject *) Py_TYPE(value);
1819 tb = PyException_GetTraceback(value);
1820 if (tb && tb != Py_None)
1821 err = PyTraceBack_Print(tb, f);
1822 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001823 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 {
1825 PyObject *message;
1826 const char *filename, *text;
1827 int lineno, offset;
1828 if (!parse_syntax_error(value, &message, &filename,
1829 &lineno, &offset, &text))
1830 PyErr_Clear();
1831 else {
1832 char buf[10];
1833 PyFile_WriteString(" File \"", f);
1834 if (filename == NULL)
1835 PyFile_WriteString("<string>", f);
1836 else
1837 PyFile_WriteString(filename, f);
1838 PyFile_WriteString("\", line ", f);
1839 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1840 PyFile_WriteString(buf, f);
1841 PyFile_WriteString("\n", f);
1842 if (text != NULL)
1843 print_error_text(f, offset, text);
1844 Py_DECREF(value);
1845 value = message;
1846 /* Can't be bothered to check all those
1847 PyFile_WriteString() calls */
1848 if (PyErr_Occurred())
1849 err = -1;
1850 }
1851 }
1852 if (err) {
1853 /* Don't do anything else */
1854 }
1855 else {
1856 PyObject* moduleName;
1857 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001858 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 assert(PyExceptionClass_Check(type));
1860 className = PyExceptionClass_Name(type);
1861 if (className != NULL) {
1862 char *dot = strrchr(className, '.');
1863 if (dot != NULL)
1864 className = dot+1;
1865 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001866
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001867 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1869 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001870 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 err = PyFile_WriteString("<unknown>", f);
1872 }
1873 else {
1874 char* modstr = _PyUnicode_AsString(moduleName);
1875 if (modstr && strcmp(modstr, "builtins"))
1876 {
1877 err = PyFile_WriteString(modstr, f);
1878 err += PyFile_WriteString(".", f);
1879 }
1880 Py_DECREF(moduleName);
1881 }
1882 if (err == 0) {
1883 if (className == NULL)
1884 err = PyFile_WriteString("<unknown>", f);
1885 else
1886 err = PyFile_WriteString(className, f);
1887 }
1888 }
1889 if (err == 0 && (value != Py_None)) {
1890 PyObject *s = PyObject_Str(value);
1891 /* only print colon if the str() of the
1892 object is not the empty string
1893 */
1894 if (s == NULL)
1895 err = -1;
1896 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001897 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 err = PyFile_WriteString(": ", f);
1899 if (err == 0)
1900 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1901 Py_XDECREF(s);
1902 }
1903 /* try to write a newline in any case */
1904 err += PyFile_WriteString("\n", f);
1905 Py_XDECREF(tb);
1906 Py_DECREF(value);
1907 /* If an error happened here, don't show it.
1908 XXX This is wrong, but too many callers rely on this behavior. */
1909 if (err != 0)
1910 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001911}
1912
1913static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 "\nThe above exception was the direct cause "
1915 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001916
1917static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 "\nDuring handling of the above exception, "
1919 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001920
1921static void
1922print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001924 int err = 0, res;
1925 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 if (seen != NULL) {
1928 /* Exception chaining */
1929 if (PySet_Add(seen, value) == -1)
1930 PyErr_Clear();
1931 else if (PyExceptionInstance_Check(value)) {
1932 cause = PyException_GetCause(value);
1933 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001934 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 res = PySet_Contains(seen, cause);
1936 if (res == -1)
1937 PyErr_Clear();
1938 if (res == 0) {
1939 print_exception_recursive(
1940 f, cause, seen);
1941 err |= PyFile_WriteString(
1942 cause_message, f);
1943 }
1944 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001945 else if (context &&
1946 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 res = PySet_Contains(seen, context);
1948 if (res == -1)
1949 PyErr_Clear();
1950 if (res == 0) {
1951 print_exception_recursive(
1952 f, context, seen);
1953 err |= PyFile_WriteString(
1954 context_message, f);
1955 }
1956 }
1957 Py_XDECREF(context);
1958 Py_XDECREF(cause);
1959 }
1960 }
1961 print_exception(f, value);
1962 if (err != 0)
1963 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001964}
1965
Thomas Wouters477c8d52006-05-27 19:21:47 +00001966void
1967PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 PyObject *seen;
1970 PyObject *f = PySys_GetObject("stderr");
Antoine Pitrou24201d42013-10-13 21:53:13 +02001971 if (PyExceptionInstance_Check(value)
1972 && tb != NULL && PyTraceBack_Check(tb)) {
1973 /* Put the traceback on the exception, otherwise it won't get
1974 displayed. See issue #18776. */
1975 PyObject *cur_tb = PyException_GetTraceback(value);
1976 if (cur_tb == NULL)
1977 PyException_SetTraceback(value, tb);
1978 else
1979 Py_DECREF(cur_tb);
1980 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 if (f == Py_None) {
1982 /* pass */
1983 }
1984 else if (f == NULL) {
1985 _PyObject_Dump(value);
1986 fprintf(stderr, "lost sys.stderr\n");
1987 }
1988 else {
1989 /* We choose to ignore seen being possibly NULL, and report
1990 at least the main exception (it could be a MemoryError).
1991 */
1992 seen = PySet_New(NULL);
1993 if (seen == NULL)
1994 PyErr_Clear();
1995 print_exception_recursive(f, value, seen);
1996 Py_XDECREF(seen);
1997 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001998}
1999
Guido van Rossum82598051997-03-05 00:20:32 +00002000PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002001PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002003{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 PyObject *ret = NULL;
2005 mod_ty mod;
2006 PyArena *arena = PyArena_New();
2007 if (arena == NULL)
2008 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
2011 if (mod != NULL)
2012 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
2013 PyArena_Free(arena);
2014 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002015}
2016
2017PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002018PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 PyObject *ret;
2022 mod_ty mod;
2023 PyArena *arena = PyArena_New();
2024 if (arena == NULL)
2025 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
2028 flags, NULL, arena);
2029 if (closeit)
2030 fclose(fp);
2031 if (mod == NULL) {
2032 PyArena_Free(arena);
2033 return NULL;
2034 }
2035 ret = run_mod(mod, filename, globals, locals, flags, arena);
2036 PyArena_Free(arena);
2037 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002038}
2039
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002040static void
2041flush_io(void)
2042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 PyObject *f, *r;
2044 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002045 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 /* Save the current exception */
2048 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 f = PySys_GetObject("stderr");
2051 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002052 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 if (r)
2054 Py_DECREF(r);
2055 else
2056 PyErr_Clear();
2057 }
2058 f = PySys_GetObject("stdout");
2059 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002060 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (r)
2062 Py_DECREF(r);
2063 else
2064 PyErr_Clear();
2065 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002068}
2069
Guido van Rossum82598051997-03-05 00:20:32 +00002070static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002071run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 PyCodeObject *co;
2075 PyObject *v;
2076 co = PyAST_Compile(mod, filename, flags, arena);
2077 if (co == NULL)
2078 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002079 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 Py_DECREF(co);
2081 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002082}
2083
Guido van Rossum82598051997-03-05 00:20:32 +00002084static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002085run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 PyCodeObject *co;
2089 PyObject *v;
2090 long magic;
2091 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 magic = PyMarshal_ReadLongFromFile(fp);
2094 if (magic != PyImport_GetMagicNumber()) {
2095 PyErr_SetString(PyExc_RuntimeError,
2096 "Bad magic number in .pyc file");
2097 return NULL;
2098 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002099 /* Skip mtime and size */
2100 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 (void) PyMarshal_ReadLongFromFile(fp);
2102 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 if (v == NULL || !PyCode_Check(v)) {
2104 Py_XDECREF(v);
2105 PyErr_SetString(PyExc_RuntimeError,
2106 "Bad code object in .pyc file");
2107 return NULL;
2108 }
2109 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002110 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 if (v && flags)
2112 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2113 Py_DECREF(co);
2114 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002115}
2116
Guido van Rossum82598051997-03-05 00:20:32 +00002117PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002118Py_CompileStringObject(const char *str, PyObject *filename, int start,
2119 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 PyCodeObject *co;
2122 mod_ty mod;
2123 PyArena *arena = PyArena_New();
2124 if (arena == NULL)
2125 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002126
Victor Stinner14e461d2013-08-26 22:28:21 +02002127 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if (mod == NULL) {
2129 PyArena_Free(arena);
2130 return NULL;
2131 }
2132 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2133 PyObject *result = PyAST_mod2obj(mod);
2134 PyArena_Free(arena);
2135 return result;
2136 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002137 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 PyArena_Free(arena);
2139 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002140}
2141
Victor Stinner14e461d2013-08-26 22:28:21 +02002142PyObject *
2143Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2144 PyCompilerFlags *flags, int optimize)
2145{
2146 PyObject *filename, *co;
2147 filename = PyUnicode_DecodeFSDefault(filename_str);
2148 if (filename == NULL)
2149 return NULL;
2150 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2151 Py_DECREF(filename);
2152 return co;
2153}
2154
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002155/* For use in Py_LIMITED_API */
2156#undef Py_CompileString
2157PyObject *
2158PyCompileString(const char *str, const char *filename, int start)
2159{
2160 return Py_CompileStringFlags(str, filename, start, NULL);
2161}
2162
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002163struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002164Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 struct symtable *st;
2167 mod_ty mod;
2168 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002169 PyArena *arena;
2170
2171 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 if (arena == NULL)
2173 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002176 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 if (mod == NULL) {
2178 PyArena_Free(arena);
2179 return NULL;
2180 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002181 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 PyArena_Free(arena);
2183 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002184}
2185
Victor Stinner14e461d2013-08-26 22:28:21 +02002186struct symtable *
2187Py_SymtableString(const char *str, const char *filename_str, int start)
2188{
2189 PyObject *filename;
2190 struct symtable *st;
2191
2192 filename = PyUnicode_DecodeFSDefault(filename_str);
2193 if (filename == NULL)
2194 return NULL;
2195 st = Py_SymtableStringObject(str, filename, start);
2196 Py_DECREF(filename);
2197 return st;
2198}
2199
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002200/* Preferred access to parser is through AST. */
2201mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002202PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2203 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 mod_ty mod;
2206 PyCompilerFlags localflags;
2207 perrdetail err;
2208 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002209
Victor Stinner14e461d2013-08-26 22:28:21 +02002210 node *n = PyParser_ParseStringObject(s, filename,
2211 &_PyParser_Grammar, start, &err,
2212 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if (flags == NULL) {
2214 localflags.cf_flags = 0;
2215 flags = &localflags;
2216 }
2217 if (n) {
2218 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002219 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 }
2222 else {
2223 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002224 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002226 err_free(&err);
2227 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002228}
2229
2230mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002231PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2232 PyCompilerFlags *flags, PyArena *arena)
2233{
2234 PyObject *filename;
2235 mod_ty mod;
2236 filename = PyUnicode_DecodeFSDefault(filename_str);
2237 if (filename == NULL)
2238 return NULL;
2239 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2240 Py_DECREF(filename);
2241 return mod;
2242}
2243
2244mod_ty
2245PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2246 int start, char *ps1,
2247 char *ps2, PyCompilerFlags *flags, int *errcode,
2248 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 mod_ty mod;
2251 PyCompilerFlags localflags;
2252 perrdetail err;
2253 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002254
Victor Stinner14e461d2013-08-26 22:28:21 +02002255 node *n = PyParser_ParseFileObject(fp, filename, enc,
2256 &_PyParser_Grammar,
2257 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 if (flags == NULL) {
2259 localflags.cf_flags = 0;
2260 flags = &localflags;
2261 }
2262 if (n) {
2263 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002264 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 }
2267 else {
2268 err_input(&err);
2269 if (errcode)
2270 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002271 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002272 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002273 err_free(&err);
2274 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275}
2276
Victor Stinner14e461d2013-08-26 22:28:21 +02002277mod_ty
2278PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2279 int start, char *ps1,
2280 char *ps2, PyCompilerFlags *flags, int *errcode,
2281 PyArena *arena)
2282{
2283 mod_ty mod;
2284 PyObject *filename;
2285 filename = PyUnicode_DecodeFSDefault(filename_str);
2286 if (filename == NULL)
2287 return NULL;
2288 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2289 flags, errcode, arena);
2290 Py_DECREF(filename);
2291 return mod;
2292}
2293
Guido van Rossuma110aa61994-08-29 12:50:44 +00002294/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002295
Guido van Rossuma110aa61994-08-29 12:50:44 +00002296node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002297PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 perrdetail err;
2300 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2301 &_PyParser_Grammar,
2302 start, NULL, NULL, &err, flags);
2303 if (n == NULL)
2304 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002305 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002308}
2309
Guido van Rossuma110aa61994-08-29 12:50:44 +00002310/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002311
Guido van Rossuma110aa61994-08-29 12:50:44 +00002312node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002313PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 perrdetail err;
2316 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2317 start, &err, flags);
2318 if (n == NULL)
2319 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002320 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002322}
2323
2324node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002325PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 perrdetail err;
2329 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2330 &_PyParser_Grammar, start, &err, flags);
2331 if (n == NULL)
2332 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002333 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002335}
2336
2337node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002338PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002341}
2342
Guido van Rossum66ebd912003-04-17 16:02:26 +00002343/* May want to move a more generalized form of this to parsetok.c or
2344 even parser modules. */
2345
2346void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002347PyParser_ClearError(perrdetail *err)
2348{
2349 err_free(err);
2350}
2351
2352void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002353PyParser_SetError(perrdetail *err)
2354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002356}
2357
Victor Stinner7f2fee32011-04-05 00:39:01 +02002358static void
2359err_free(perrdetail *err)
2360{
2361 Py_CLEAR(err->filename);
2362}
2363
Guido van Rossuma110aa61994-08-29 12:50:44 +00002364/* Set the error appropriate to the given input error code (see errcode.h) */
2365
2366static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002367err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 PyObject *v, *w, *errtype, *errtext;
2370 PyObject *msg_obj = NULL;
2371 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 errtype = PyExc_SyntaxError;
2374 switch (err->error) {
2375 case E_ERROR:
2376 return;
2377 case E_SYNTAX:
2378 errtype = PyExc_IndentationError;
2379 if (err->expected == INDENT)
2380 msg = "expected an indented block";
2381 else if (err->token == INDENT)
2382 msg = "unexpected indent";
2383 else if (err->token == DEDENT)
2384 msg = "unexpected unindent";
2385 else {
2386 errtype = PyExc_SyntaxError;
2387 msg = "invalid syntax";
2388 }
2389 break;
2390 case E_TOKEN:
2391 msg = "invalid token";
2392 break;
2393 case E_EOFS:
2394 msg = "EOF while scanning triple-quoted string literal";
2395 break;
2396 case E_EOLS:
2397 msg = "EOL while scanning string literal";
2398 break;
2399 case E_INTR:
2400 if (!PyErr_Occurred())
2401 PyErr_SetNone(PyExc_KeyboardInterrupt);
2402 goto cleanup;
2403 case E_NOMEM:
2404 PyErr_NoMemory();
2405 goto cleanup;
2406 case E_EOF:
2407 msg = "unexpected EOF while parsing";
2408 break;
2409 case E_TABSPACE:
2410 errtype = PyExc_TabError;
2411 msg = "inconsistent use of tabs and spaces in indentation";
2412 break;
2413 case E_OVERFLOW:
2414 msg = "expression too long";
2415 break;
2416 case E_DEDENT:
2417 errtype = PyExc_IndentationError;
2418 msg = "unindent does not match any outer indentation level";
2419 break;
2420 case E_TOODEEP:
2421 errtype = PyExc_IndentationError;
2422 msg = "too many levels of indentation";
2423 break;
2424 case E_DECODE: {
2425 PyObject *type, *value, *tb;
2426 PyErr_Fetch(&type, &value, &tb);
2427 msg = "unknown decode error";
2428 if (value != NULL)
2429 msg_obj = PyObject_Str(value);
2430 Py_XDECREF(type);
2431 Py_XDECREF(value);
2432 Py_XDECREF(tb);
2433 break;
2434 }
2435 case E_LINECONT:
2436 msg = "unexpected character after line continuation character";
2437 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 case E_IDENTIFIER:
2440 msg = "invalid character in identifier";
2441 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002442 case E_BADSINGLE:
2443 msg = "multiple statements found while compiling a single statement";
2444 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 default:
2446 fprintf(stderr, "error=%d\n", err->error);
2447 msg = "unknown parsing error";
2448 break;
2449 }
2450 /* err->text may not be UTF-8 in case of decoding errors.
2451 Explicitly convert to an object. */
2452 if (!err->text) {
2453 errtext = Py_None;
2454 Py_INCREF(Py_None);
2455 } else {
2456 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2457 "replace");
2458 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002459 v = Py_BuildValue("(OiiN)", err->filename,
2460 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (v != NULL) {
2462 if (msg_obj)
2463 w = Py_BuildValue("(OO)", msg_obj, v);
2464 else
2465 w = Py_BuildValue("(sO)", msg, v);
2466 } else
2467 w = NULL;
2468 Py_XDECREF(v);
2469 PyErr_SetObject(errtype, w);
2470 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002471cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 Py_XDECREF(msg_obj);
2473 if (err->text != NULL) {
2474 PyObject_FREE(err->text);
2475 err->text = NULL;
2476 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002477}
2478
2479/* Print fatal error message and abort */
2480
2481void
Tim Peters7c321a82002-07-09 02:57:01 +00002482Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002483{
Victor Stinner024e37a2011-03-31 01:31:06 +02002484 const int fd = fileno(stderr);
2485 PyThreadState *tstate;
2486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 fprintf(stderr, "Fatal Python error: %s\n", msg);
2488 fflush(stderr); /* it helps in Windows debug build */
2489 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002490 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002492 else {
2493 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2494 if (tstate != NULL) {
2495 fputc('\n', stderr);
2496 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002497 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002498 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002499 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002500 }
2501
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002502#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 {
2504 size_t len = strlen(msg);
2505 WCHAR* buffer;
2506 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 /* Convert the message to wchar_t. This uses a simple one-to-one
2509 conversion, assuming that the this error message actually uses ASCII
2510 only. If this ceases to be true, we will have to convert. */
2511 buffer = alloca( (len+1) * (sizeof *buffer));
2512 for( i=0; i<=len; ++i)
2513 buffer[i] = msg[i];
2514 OutputDebugStringW(L"Fatal Python error: ");
2515 OutputDebugStringW(buffer);
2516 OutputDebugStringW(L"\n");
2517 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002518#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002520#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002521#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002523}
2524
2525/* Clean up and exit */
2526
Guido van Rossuma110aa61994-08-29 12:50:44 +00002527#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002528#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002529#endif
2530
Collin Winter670e6922007-03-21 02:57:17 +00002531static void (*pyexitfunc)(void) = NULL;
2532/* For the atexit module. */
2533void _Py_PyAtExit(void (*func)(void))
2534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002536}
2537
2538static void
2539call_py_exitfuncs(void)
2540{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 if (pyexitfunc == NULL)
2542 return;
Collin Winter670e6922007-03-21 02:57:17 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 (*pyexitfunc)();
2545 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002546}
2547
Antoine Pitrou011bd622009-10-20 21:52:47 +00002548/* Wait until threading._shutdown completes, provided
2549 the threading module was imported in the first place.
2550 The shutdown routine will wait until all non-daemon
2551 "threading" threads have completed. */
2552static void
2553wait_for_thread_shutdown(void)
2554{
2555#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002556 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 PyObject *result;
2558 PyThreadState *tstate = PyThreadState_GET();
2559 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2560 "threading");
2561 if (threading == NULL) {
2562 /* threading not imported */
2563 PyErr_Clear();
2564 return;
2565 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002566 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 if (result == NULL) {
2568 PyErr_WriteUnraisable(threading);
2569 }
2570 else {
2571 Py_DECREF(result);
2572 }
2573 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002574#endif
2575}
2576
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002577#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002578static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002579static int nexitfuncs = 0;
2580
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002581int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 if (nexitfuncs >= NEXITFUNCS)
2584 return -1;
2585 exitfuncs[nexitfuncs++] = func;
2586 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002587}
2588
Guido van Rossumcc283f51997-08-05 02:22:03 +00002589static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002590call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 while (nexitfuncs > 0)
2593 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 fflush(stdout);
2596 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002597}
2598
2599void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002600Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002601{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002605}
2606
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002607static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002608initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002609{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002610#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002612#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002613#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002615#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002616#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002618#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002620 if (PyErr_Occurred()) {
2621 Py_FatalError("Py_Initialize: can't import signal");
2622 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002623}
2624
Guido van Rossum7433b121997-02-14 19:45:36 +00002625
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002626/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2627 *
2628 * All of the code in this function must only use async-signal-safe functions,
2629 * listed at `man 7 signal` or
2630 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2631 */
2632void
2633_Py_RestoreSignals(void)
2634{
2635#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002637#endif
2638#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002640#endif
2641#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002643#endif
2644}
2645
2646
Guido van Rossum7433b121997-02-14 19:45:36 +00002647/*
2648 * The file descriptor fd is considered ``interactive'' if either
2649 * a) isatty(fd) is TRUE, or
2650 * b) the -i flag was given, and the filename associated with
2651 * the descriptor is NULL or "<stdin>" or "???".
2652 */
2653int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002654Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 if (isatty((int)fileno(fp)))
2657 return 1;
2658 if (!Py_InteractiveFlag)
2659 return 0;
2660 return (filename == NULL) ||
2661 (strcmp(filename, "<stdin>") == 0) ||
2662 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002663}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002664
2665
Tim Petersd08e3822003-04-17 15:24:21 +00002666#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002667#if defined(WIN32) && defined(_MSC_VER)
2668
2669/* Stack checking for Microsoft C */
2670
2671#include <malloc.h>
2672#include <excpt.h>
2673
Fred Drakee8de31c2000-08-31 05:38:39 +00002674/*
2675 * Return non-zero when we run out of memory on the stack; zero otherwise.
2676 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002677int
Fred Drake399739f2000-08-31 05:52:44 +00002678PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 __try {
2681 /* alloca throws a stack overflow exception if there's
2682 not enough space left on the stack */
2683 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2684 return 0;
2685 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2686 EXCEPTION_EXECUTE_HANDLER :
2687 EXCEPTION_CONTINUE_SEARCH) {
2688 int errcode = _resetstkoflw();
2689 if (errcode == 0)
2690 {
2691 Py_FatalError("Could not reset the stack!");
2692 }
2693 }
2694 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002695}
2696
2697#endif /* WIN32 && _MSC_VER */
2698
2699/* Alternate implementations can be added here... */
2700
2701#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002702
2703
2704/* Wrappers around sigaction() or signal(). */
2705
2706PyOS_sighandler_t
2707PyOS_getsig(int sig)
2708{
2709#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 struct sigaction context;
2711 if (sigaction(sig, NULL, &context) == -1)
2712 return SIG_ERR;
2713 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002714#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002716/* Special signal handling for the secure CRT in Visual Studio 2005 */
2717#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 switch (sig) {
2719 /* Only these signals are valid */
2720 case SIGINT:
2721 case SIGILL:
2722 case SIGFPE:
2723 case SIGSEGV:
2724 case SIGTERM:
2725 case SIGBREAK:
2726 case SIGABRT:
2727 break;
2728 /* Don't call signal() with other values or it will assert */
2729 default:
2730 return SIG_ERR;
2731 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002732#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 handler = signal(sig, SIG_IGN);
2734 if (handler != SIG_ERR)
2735 signal(sig, handler);
2736 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002737#endif
2738}
2739
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002740/*
2741 * All of the code in this function must only use async-signal-safe functions,
2742 * listed at `man 7 signal` or
2743 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2744 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002745PyOS_sighandler_t
2746PyOS_setsig(int sig, PyOS_sighandler_t handler)
2747{
2748#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 /* Some code in Modules/signalmodule.c depends on sigaction() being
2750 * used here if HAVE_SIGACTION is defined. Fix that if this code
2751 * changes to invalidate that assumption.
2752 */
2753 struct sigaction context, ocontext;
2754 context.sa_handler = handler;
2755 sigemptyset(&context.sa_mask);
2756 context.sa_flags = 0;
2757 if (sigaction(sig, &context, &ocontext) == -1)
2758 return SIG_ERR;
2759 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002760#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 PyOS_sighandler_t oldhandler;
2762 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002763#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002765#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002767#endif
2768}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002769
2770/* Deprecated C API functions still provided for binary compatiblity */
2771
2772#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002773PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002774PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2775{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002777}
2778
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002779#undef PyParser_SimpleParseString
2780PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002781PyParser_SimpleParseString(const char *str, int start)
2782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002784}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002785
2786#undef PyRun_AnyFile
2787PyAPI_FUNC(int)
2788PyRun_AnyFile(FILE *fp, const char *name)
2789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002791}
2792
2793#undef PyRun_AnyFileEx
2794PyAPI_FUNC(int)
2795PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002798}
2799
2800#undef PyRun_AnyFileFlags
2801PyAPI_FUNC(int)
2802PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002805}
2806
2807#undef PyRun_File
2808PyAPI_FUNC(PyObject *)
2809PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002812}
2813
2814#undef PyRun_FileEx
2815PyAPI_FUNC(PyObject *)
2816PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002819}
2820
2821#undef PyRun_FileFlags
2822PyAPI_FUNC(PyObject *)
2823PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002827}
2828
2829#undef PyRun_SimpleFile
2830PyAPI_FUNC(int)
2831PyRun_SimpleFile(FILE *f, const char *p)
2832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002834}
2835
2836#undef PyRun_SimpleFileEx
2837PyAPI_FUNC(int)
2838PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002841}
2842
2843
2844#undef PyRun_String
2845PyAPI_FUNC(PyObject *)
2846PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002848 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002849}
2850
2851#undef PyRun_SimpleString
2852PyAPI_FUNC(int)
2853PyRun_SimpleString(const char *s)
2854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002856}
2857
2858#undef Py_CompileString
2859PyAPI_FUNC(PyObject *)
2860Py_CompileString(const char *str, const char *p, int s)
2861{
Georg Brandl8334fd92010-12-04 10:26:46 +00002862 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2863}
2864
2865#undef Py_CompileStringFlags
2866PyAPI_FUNC(PyObject *)
2867Py_CompileStringFlags(const char *str, const char *p, int s,
2868 PyCompilerFlags *flags)
2869{
2870 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002871}
2872
2873#undef PyRun_InteractiveOne
2874PyAPI_FUNC(int)
2875PyRun_InteractiveOne(FILE *f, const char *p)
2876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002877 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002878}
2879
2880#undef PyRun_InteractiveLoop
2881PyAPI_FUNC(int)
2882PyRun_InteractiveLoop(FILE *f, const char *p)
2883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002885}
2886
2887#ifdef __cplusplus
2888}
2889#endif