blob: e510e6f78abba98bc91ced8bbcbe7bfd325553bb [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
Victor Stinner09054372013-11-06 22:41:44 +010038/* Common identifiers */
39_Py_Identifier _PyId_argv = _Py_static_string_init("argv");
40_Py_Identifier _PyId_path = _Py_static_string_init("path");
41_Py_Identifier _PyId_stdin = _Py_static_string_init("stdin");
42_Py_Identifier _PyId_stdout = _Py_static_string_init("stdout");
43_Py_Identifier _PyId_stderr = _Py_static_string_init("stderr");
44
45/* local identifiers */
46_Py_IDENTIFIER(excepthook);
47_Py_IDENTIFIER(ps1);
48_Py_IDENTIFIER(ps2);
49_Py_IDENTIFIER(last_type);
50_Py_IDENTIFIER(last_value);
51_Py_IDENTIFIER(last_traceback);
52
Ezio Melotti1f8898a2013-03-26 01:59:56 +020053#ifdef Py_REF_DEBUG
Antoine Pitrou208ac5c2013-04-24 20:17:53 +020054static
55void _print_total_refs(void) {
Victor Stinner4ee41c52013-11-06 18:28:21 +010056 PyObject *xoptions, *value;
57 _Py_IDENTIFIER(showrefcount);
58
Ezio Melotti1f8898a2013-03-26 01:59:56 +020059 xoptions = PySys_GetXOptions();
60 if (xoptions == NULL)
61 return;
Victor Stinner4ee41c52013-11-06 18:28:21 +010062 value = _PyDict_GetItemId(xoptions, &PyId_showrefcount);
Ezio Melotti1f8898a2013-03-26 01:59:56 +020063 if (value == Py_True)
64 fprintf(stderr,
65 "[%" PY_FORMAT_SIZE_T "d refs, "
66 "%" PY_FORMAT_SIZE_T "d blocks]\n",
67 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
68}
69#endif
70
Neal Norwitz4281cef2006-03-04 19:58:13 +000071#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000072#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000073#else /* Py_REF_DEBUG */
Ezio Melotti1f8898a2013-03-26 01:59:56 +020074#define PRINT_TOTAL_REFS() _print_total_refs()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000075#endif
76
77#ifdef __cplusplus
78extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000079#endif
80
Martin v. Löwis790465f2008-04-05 20:41:37 +000081extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000082
Guido van Rossum82598051997-03-05 00:20:32 +000083extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000084
Guido van Rossumb73cc041993-11-01 16:28:59 +000085/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100086static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020087static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000088static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000089static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000090static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010091static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000093static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000095static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020096static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000097static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000098static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000099static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000100static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +0200101extern int _PyUnicode_Init(void);
Victor Stinner26f91992013-07-17 01:22:45 +0200102extern int _PyStructSequence_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000103extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000104extern int _PyLong_Init(void);
105extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +0200106extern int _PyFaulthandler_Init(void);
107extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +0000108
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000109#ifdef WITH_THREAD
110extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
111extern void _PyGILState_Fini(void);
112#endif /* WITH_THREAD */
113
Guido van Rossum82598051997-03-05 00:20:32 +0000114int Py_DebugFlag; /* Needed by parser.c */
115int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000116int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000117int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200118int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000119int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000120int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000121int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000122int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000123int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000124int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000125int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000126int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100127int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200128int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000129
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200130PyThreadState *_Py_Finalizing = NULL;
131
Christian Heimes49e61802013-10-22 10:22:29 +0200132/* Hack to force loading of object files */
133int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
134 PyOS_mystrnicmp; /* Python/pystrcmp.o */
135
Christian Heimes33fe8092008-04-13 13:53:33 +0000136/* PyModule_GetWarningsModule is no longer necessary as of 2.6
137since _warnings is builtin. This API should not be used. */
138PyObject *
139PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000142}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000143
Guido van Rossum25ce5661997-08-02 03:10:38 +0000144static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000145
Thomas Wouters7e474022000-07-16 12:04:32 +0000146/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000147
148int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000149Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000152}
153
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000154/* Helper to allow an embedding application to override the normal
155 * mechanism that attempts to figure out an appropriate IO encoding
156 */
157
158static char *_Py_StandardStreamEncoding = NULL;
159static char *_Py_StandardStreamErrors = NULL;
160
161int
162Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
163{
164 if (Py_IsInitialized()) {
165 /* This is too late to have any effect */
166 return -1;
167 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000168 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
169 * initialised yet.
170 *
171 * However, the raw memory allocators are initialised appropriately
172 * as C static variables, so _PyMem_RawStrdup is OK even though
173 * Py_Initialize hasn't been called yet.
174 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000175 if (encoding) {
176 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
177 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000178 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000179 }
180 }
181 if (errors) {
182 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
183 if (!_Py_StandardStreamErrors) {
184 if (_Py_StandardStreamEncoding) {
185 PyMem_RawFree(_Py_StandardStreamEncoding);
186 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000187 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000188 }
189 }
190 return 0;
191}
192
Guido van Rossum25ce5661997-08-02 03:10:38 +0000193/* Global initializations. Can be undone by Py_Finalize(). Don't
194 call this twice without an intervening Py_Finalize() call. When
195 initializations fail, a fatal error is issued and the function does
196 not return. On return, the first thread and interpreter state have
197 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000198
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199 Locking: you must hold the interpreter lock while calling this.
200 (If the lock has not yet been initialized, that's equivalent to
201 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000202
Guido van Rossum25ce5661997-08-02 03:10:38 +0000203*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000205static int
206add_flag(int flag, const char *envs)
207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 int env = atoi(envs);
209 if (flag < env)
210 flag = env;
211 if (flag < 1)
212 flag = 1;
213 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000214}
215
Christian Heimes5833a2f2008-10-30 21:40:04 +0000216static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000217get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000218{
Victor Stinner94908bb2010-08-18 21:23:25 +0000219 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000220 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200221 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000222
Victor Stinner94908bb2010-08-18 21:23:25 +0000223 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 if (!codec)
225 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000226
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200227 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 Py_CLEAR(codec);
229 if (!name)
230 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000231
Victor Stinner94908bb2010-08-18 21:23:25 +0000232 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100233 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000234 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200235 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000237 if (name_str == NULL) {
238 PyErr_NoMemory();
239 return NULL;
240 }
241 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000242
243error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000245 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000247}
Victor Stinner94908bb2010-08-18 21:23:25 +0000248
Victor Stinner94908bb2010-08-18 21:23:25 +0000249static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200250get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000251{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200252#ifdef MS_WINDOWS
253 char codepage[100];
254 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
255 return get_codec_name(codepage);
256#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000257 char* codeset = nl_langinfo(CODESET);
258 if (!codeset || codeset[0] == '\0') {
259 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
260 return NULL;
261 }
262 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200263#else
264 PyErr_SetNone(PyExc_NotImplementedError);
265 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000266#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200267}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000268
Brett Cannonfd074152012-04-14 14:10:13 -0400269static void
270import_init(PyInterpreterState *interp, PyObject *sysmod)
271{
272 PyObject *importlib;
273 PyObject *impmod;
274 PyObject *sys_modules;
275 PyObject *value;
276
277 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400278 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
279 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
280 }
281 else if (Py_VerboseFlag) {
282 PySys_FormatStderr("import _frozen_importlib # frozen\n");
283 }
284 importlib = PyImport_AddModule("_frozen_importlib");
285 if (importlib == NULL) {
286 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
287 "sys.modules");
288 }
289 interp->importlib = importlib;
290 Py_INCREF(interp->importlib);
291
292 /* Install _importlib as __import__ */
293 impmod = PyInit_imp();
294 if (impmod == NULL) {
295 Py_FatalError("Py_Initialize: can't import imp");
296 }
297 else if (Py_VerboseFlag) {
298 PySys_FormatStderr("import imp # builtin\n");
299 }
300 sys_modules = PyImport_GetModuleDict();
301 if (Py_VerboseFlag) {
302 PySys_FormatStderr("import sys # builtin\n");
303 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400304 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
305 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400306 }
307
Brett Cannone0d88a12012-04-25 20:54:04 -0400308 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400309 if (value == NULL) {
310 PyErr_Print();
311 Py_FatalError("Py_Initialize: importlib install failed");
312 }
313 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400314 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400315
316 _PyImportZip_Init();
317}
318
319
Guido van Rossuma027efa1997-05-05 20:56:21 +0000320void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200321_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 PyInterpreterState *interp;
324 PyThreadState *tstate;
325 PyObject *bimod, *sysmod, *pstderr;
326 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (initialized)
330 return;
331 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200332 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000333
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000334#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 /* Set up the LC_CTYPE locale, so we can obtain
336 the locale's charset without having to switch
337 locales. */
338 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000339#endif
340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
342 Py_DebugFlag = add_flag(Py_DebugFlag, p);
343 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
344 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
345 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
346 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
347 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
348 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100349 /* The variable is only tested for existence here; _PyRandom_Init will
350 check its value further. */
351 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
352 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
353
354 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 interp = PyInterpreterState_New();
357 if (interp == NULL)
358 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 tstate = PyThreadState_New(interp);
361 if (tstate == NULL)
362 Py_FatalError("Py_Initialize: can't make first thread");
363 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000364
Victor Stinner6961bd62010-08-17 22:26:51 +0000365#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000366 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
367 destroying the GIL might fail when it is being referenced from
368 another running thread (see issue #9901).
369 Instead we destroy the previously created GIL here, which ensures
370 that we can call Py_Initialize / Py_Finalize multiple times. */
371 _PyEval_FiniThreads();
372
373 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000374 _PyGILState_Init(interp, tstate);
375#endif /* WITH_THREAD */
376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (!_PyFrame_Init())
380 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (!_PyLong_Init())
383 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 if (!PyByteArray_Init())
386 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000387
Victor Stinner1c8f0592013-07-22 22:24:54 +0200388 if (!_PyFloat_Init())
389 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 interp->modules = PyDict_New();
392 if (interp->modules == NULL)
393 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200396 if (_PyUnicode_Init() < 0)
397 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200398 if (_PyStructSequence_Init() < 0)
399 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 bimod = _PyBuiltin_Init();
402 if (bimod == NULL)
403 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000404 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 interp->builtins = PyModule_GetDict(bimod);
406 if (interp->builtins == NULL)
407 Py_FatalError("Py_Initialize: can't initialize builtins dict");
408 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400411 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 sysmod = _PySys_Init();
414 if (sysmod == NULL)
415 Py_FatalError("Py_Initialize: can't initialize sys");
416 interp->sysdict = PyModule_GetDict(sysmod);
417 if (interp->sysdict == NULL)
418 Py_FatalError("Py_Initialize: can't initialize sys dict");
419 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000420 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PySys_SetPath(Py_GetPath());
422 PyDict_SetItemString(interp->sysdict, "modules",
423 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 /* Set up a preliminary stderr printer until we have enough
426 infrastructure for the io module in place. */
427 pstderr = PyFile_NewStdPrinter(fileno(stderr));
428 if (pstderr == NULL)
429 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinner09054372013-11-06 22:41:44 +0100430 _PySys_SetObjectId(&_PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000432 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000437
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000438 /* Initialize _warnings. */
439 _PyWarnings_Init();
440
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200441 if (!install_importlib)
442 return;
443
Brett Cannonfd074152012-04-14 14:10:13 -0400444 import_init(interp, sysmod);
445
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200446 /* initialize the faulthandler module */
447 if (_PyFaulthandler_Init())
448 Py_FatalError("Py_Initialize: can't initialize faulthandler");
449
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000450 _PyTime_Init();
451
Victor Stinner793b5312011-04-27 00:24:21 +0200452 if (initfsencoding(interp) < 0)
453 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (install_sigs)
456 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000457
Nick Coghlan85e729e2012-07-15 18:09:52 +1000458 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (initstdio() < 0)
460 Py_FatalError(
461 "Py_Initialize: can't initialize sys standard streams");
462
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000463 /* Initialize warnings. */
464 if (PySys_HasWarnOptions()) {
465 PyObject *warnings_module = PyImport_ImportModule("warnings");
466 if (warnings_module == NULL) {
467 fprintf(stderr, "'import warnings' failed; traceback:\n");
468 PyErr_Print();
469 }
470 Py_XDECREF(warnings_module);
471 }
472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (!Py_NoSiteFlag)
474 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000475}
476
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000477void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200478Py_InitializeEx(int install_sigs)
479{
480 _Py_InitializeEx_Private(install_sigs, 1);
481}
482
483void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000484Py_Initialize(void)
485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000487}
488
489
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000490#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000491extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000492#endif
493
Guido van Rossume8432ac2007-07-09 15:04:50 +0000494/* Flush stdout and stderr */
495
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100496static int
497file_is_closed(PyObject *fobj)
498{
499 int r;
500 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
501 if (tmp == NULL) {
502 PyErr_Clear();
503 return 0;
504 }
505 r = PyObject_IsTrue(tmp);
506 Py_DECREF(tmp);
507 if (r < 0)
508 PyErr_Clear();
509 return r > 0;
510}
511
Neal Norwitz2bad9702007-08-27 06:19:22 +0000512static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000513flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000514{
Victor Stinner09054372013-11-06 22:41:44 +0100515 PyObject *fout = _PySys_GetObjectId(&_PyId_stdout);
516 PyObject *ferr = _PySys_GetObjectId(&_PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200518 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000519
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100520 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200521 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000523 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 else
525 Py_DECREF(tmp);
526 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000527
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100528 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200529 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (tmp == NULL)
531 PyErr_Clear();
532 else
533 Py_DECREF(tmp);
534 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000535}
536
Guido van Rossum25ce5661997-08-02 03:10:38 +0000537/* Undo the effect of Py_Initialize().
538
539 Beware: if multiple interpreter and/or thread states exist, these
540 are not wiped out; only the current thread and interpreter state
541 are deleted. But since everything else is deleted, those other
542 interpreter and thread states should no longer be used.
543
544 (XXX We should do better, e.g. wipe out all interpreters and
545 threads.)
546
547 Locking: as above.
548
549*/
550
551void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000552Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 PyInterpreterState *interp;
555 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (!initialized)
558 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* The interpreter is still entirely intact at this point, and the
563 * exit funcs may be relying on that. In particular, if some thread
564 * or exit func is still waiting to do an import, the import machinery
565 * expects Py_IsInitialized() to return true. So don't say the
566 * interpreter is uninitialized until after the exit funcs have run.
567 * Note that Threading.py uses an exit func to do a join on all the
568 * threads created thru it, so this also protects pending imports in
569 * the threads created via Threading.
570 */
571 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 /* Get current thread state and interpreter pointer */
574 tstate = PyThreadState_GET();
575 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200577 /* Remaining threads (e.g. daemon threads) will automatically exit
578 after taking the GIL (in PyEval_RestoreThread()). */
579 _Py_Finalizing = tstate;
580 initialized = 0;
581
582 /* Flush stdout+stderr */
583 flush_std_files();
584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 /* Disable signal handling */
586 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* Collect garbage. This may call finalizers; it's nice to call these
589 * before all modules are destroyed.
590 * XXX If a __del__ or weakref callback is triggered here, and tries to
591 * XXX import a module, bad things can happen, because Python no
592 * XXX longer believes it's initialized.
593 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
594 * XXX is easy to provoke that way. I've also seen, e.g.,
595 * XXX Exception exceptions.ImportError: 'No module named sha'
596 * XXX in <function callback at 0x008F5718> ignored
597 * XXX but I'm unclear on exactly how that one happens. In any case,
598 * XXX I haven't seen a real-life report of either of these.
599 */
600 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000601#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 /* With COUNT_ALLOCS, it helps to run GC multiple times:
603 each collection might release some types from the type
604 list, so they become garbage. */
605 while (PyGC_Collect() > 0)
606 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000607#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* Destroy all modules */
609 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 /* Flush stdout+stderr (again, in case more was printed) */
612 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100615 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 * XXX This is disabled because it caused too many problems. If
617 * XXX a __del__ or weakref callback triggers here, Python code has
618 * XXX a hard time running, because even the sys module has been
619 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
620 * XXX One symptom is a sequence of information-free messages
621 * XXX coming from threads (if a __del__ or callback is invoked,
622 * XXX other threads can execute too, and any exception they encounter
623 * XXX triggers a comedy of errors as subsystem after subsystem
624 * XXX fails to find what it *expects* to find in sys to help report
625 * XXX the exception and consequent unexpected failures). I've also
626 * XXX seen segfaults then, after adding print statements to the
627 * XXX Python code getting called.
628 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000629#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000631#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
634 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000635
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200636 /* Cleanup typeobject.c's internal caches. */
637 _PyType_Fini();
638
Victor Stinner024e37a2011-03-31 01:31:06 +0200639 /* unload faulthandler module */
640 _PyFaulthandler_Fini();
641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000643#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000645#endif
646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000648
Tim Peters9cf25ce2003-04-17 15:21:01 +0000649#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 /* Display all objects still alive -- this can invoke arbitrary
651 * __repr__ overrides, so requires a mostly-intact interpreter.
652 * Alas, a lot of stuff may still be alive now that will be cleaned
653 * up later.
654 */
655 if (Py_GETENV("PYTHONDUMPREFS"))
656 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000657#endif /* Py_TRACE_REFS */
658
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200659 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 /* Now we decref the exception classes. After this point nothing
663 can raise an exception. That's okay, because each Fini() method
664 below has been checked to make sure no exceptions are ever
665 raised.
666 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 /* Sundry finalizers */
671 PyMethod_Fini();
672 PyFrame_Fini();
673 PyCFunction_Fini();
674 PyTuple_Fini();
675 PyList_Fini();
676 PySet_Fini();
677 PyBytes_Fini();
678 PyByteArray_Fini();
679 PyLong_Fini();
680 PyFloat_Fini();
681 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100682 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200683 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200684 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 /* Cleanup Unicode implementation */
687 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000690 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200691 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 Py_FileSystemDefaultEncoding = NULL;
693 }
Christian Heimesc8967002007-11-30 10:18:26 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 /* XXX Still allocated:
696 - various static ad-hoc pointers to interned strings
697 - int and float free list blocks
698 - whatever various modules and libraries allocate
699 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000702
Victor Stinner51fa4582013-07-07 15:50:49 +0200703 /* Cleanup auto-thread-state */
704#ifdef WITH_THREAD
705 _PyGILState_Fini();
706#endif /* WITH_THREAD */
707
708 /* Delete current thread. After this, many C API calls become crashy. */
709 PyThreadState_Swap(NULL);
710 PyInterpreterState_Delete(interp);
711
Tim Peters269b2a62003-04-17 19:52:29 +0000712#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 /* Display addresses (& refcnts) of all objects still alive.
714 * An address can be used to find the repr of the object, printed
715 * above by _Py_PrintReferences.
716 */
717 if (Py_GETENV("PYTHONDUMPREFS"))
718 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000719#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000720#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400722 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000723#endif
724
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000726}
727
728/* Create and initialize a new interpreter and thread, and return the
729 new thread. This requires that Py_Initialize() has been called
730 first.
731
732 Unsuccessful initialization yields a NULL pointer. Note that *no*
733 exception information is available even in this case -- the
734 exception information is held in the thread, and there is no
735 thread.
736
737 Locking: as above.
738
739*/
740
741PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000742Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 PyInterpreterState *interp;
745 PyThreadState *tstate, *save_tstate;
746 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 if (!initialized)
749 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 interp = PyInterpreterState_New();
752 if (interp == NULL)
753 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000754
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 tstate = PyThreadState_New(interp);
756 if (tstate == NULL) {
757 PyInterpreterState_Delete(interp);
758 return NULL;
759 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000766
Victor Stinner49d3f252010-10-17 01:24:53 +0000767 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (bimod != NULL) {
769 interp->builtins = PyModule_GetDict(bimod);
770 if (interp->builtins == NULL)
771 goto handle_error;
772 Py_INCREF(interp->builtins);
773 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400776 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000777
Victor Stinner49d3f252010-10-17 01:24:53 +0000778 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (bimod != NULL && sysmod != NULL) {
780 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 interp->sysdict = PyModule_GetDict(sysmod);
783 if (interp->sysdict == NULL)
784 goto handle_error;
785 Py_INCREF(interp->sysdict);
786 PySys_SetPath(Py_GetPath());
787 PyDict_SetItemString(interp->sysdict, "modules",
788 interp->modules);
789 /* Set up a preliminary stderr printer until we have enough
790 infrastructure for the io module in place. */
791 pstderr = PyFile_NewStdPrinter(fileno(stderr));
792 if (pstderr == NULL)
793 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinner09054372013-11-06 22:41:44 +0100794 _PySys_SetObjectId(&_PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000796 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200799
Brett Cannonfd074152012-04-14 14:10:13 -0400800 import_init(interp, sysmod);
801
Victor Stinner793b5312011-04-27 00:24:21 +0200802 if (initfsencoding(interp) < 0)
803 goto handle_error;
804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 if (initstdio() < 0)
806 Py_FatalError(
807 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000808 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 if (!Py_NoSiteFlag)
810 initsite();
811 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (!PyErr_Occurred())
814 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000815
Thomas Wouters89f507f2006-12-13 04:49:30 +0000816handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000818
Victor Stinnerc40a3502011-04-27 00:20:27 +0200819 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 PyThreadState_Clear(tstate);
821 PyThreadState_Swap(save_tstate);
822 PyThreadState_Delete(tstate);
823 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000826}
827
828/* Delete an interpreter and its last thread. This requires that the
829 given thread state is current, that the thread has no remaining
830 frames, and that it is its interpreter's only remaining thread.
831 It is a fatal error to violate these constraints.
832
833 (Py_Finalize() doesn't have these constraints -- it zaps
834 everything, regardless.)
835
836 Locking: as above.
837
838*/
839
840void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000841Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 if (tstate != PyThreadState_GET())
846 Py_FatalError("Py_EndInterpreter: thread is not current");
847 if (tstate->frame != NULL)
848 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200849
850 wait_for_thread_shutdown();
851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (tstate != interp->tstate_head || tstate->next != NULL)
853 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 PyImport_Cleanup();
856 PyInterpreterState_Clear(interp);
857 PyThreadState_Swap(NULL);
858 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000859}
860
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200861#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000862static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200863#else
864static wchar_t *progname = L"python3";
865#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000866
867void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000868Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (pn && *pn)
871 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000872}
873
Martin v. Löwis790465f2008-04-05 20:41:37 +0000874wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000875Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000878}
879
Martin v. Löwis790465f2008-04-05 20:41:37 +0000880static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200881static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000882
883void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000884Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000887}
888
Martin v. Löwis790465f2008-04-05 20:41:37 +0000889wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000890Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 wchar_t *home = default_home;
893 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
894 char* chome = Py_GETENV("PYTHONHOME");
895 if (chome) {
896 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
897 if (r != (size_t)-1 && r <= PATH_MAX)
898 home = env_home;
899 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000900
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 }
902 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000903}
904
Guido van Rossum6135a871995-01-09 17:53:26 +0000905/* Create __main__ module */
906
907static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000908initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000909{
Brett Cannon13853a62013-05-04 17:37:09 -0400910 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 m = PyImport_AddModule("__main__");
912 if (m == NULL)
913 Py_FatalError("can't create __main__ module");
914 d = PyModule_GetDict(m);
915 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
916 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000917 if (bimod == NULL) {
918 Py_FatalError("Failed to retrieve builtins module");
919 }
920 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
921 Py_FatalError("Failed to initialize __main__.__builtins__");
922 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 Py_DECREF(bimod);
924 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000925 /* Main is a little special - imp.is_builtin("__main__") will return
926 * False, but BuiltinImporter is still the most appropriate initial
927 * setting for its __loader__ attribute. A more suitable value will
928 * be set if __main__ gets further initialized later in the startup
929 * process.
930 */
Brett Cannon13853a62013-05-04 17:37:09 -0400931 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400932 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000933 PyObject *loader = PyObject_GetAttrString(interp->importlib,
934 "BuiltinImporter");
935 if (loader == NULL) {
936 Py_FatalError("Failed to retrieve BuiltinImporter");
937 }
938 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
939 Py_FatalError("Failed to initialize __main__.__loader__");
940 }
941 Py_DECREF(loader);
942 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000943}
944
Victor Stinner793b5312011-04-27 00:24:21 +0200945static int
946initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000947{
948 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000949
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200950 if (Py_FileSystemDefaultEncoding == NULL)
951 {
952 Py_FileSystemDefaultEncoding = get_locale_encoding();
953 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000954 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000955
Victor Stinnere4743092010-10-19 00:05:51 +0000956 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200957 interp->fscodec_initialized = 1;
958 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000959 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000960
961 /* the encoding is mbcs, utf-8 or ascii */
962 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
963 if (!codec) {
964 /* Such error can only occurs in critical situations: no more
965 * memory, import a module of the standard library failed,
966 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200967 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000968 }
Victor Stinner793b5312011-04-27 00:24:21 +0200969 Py_DECREF(codec);
970 interp->fscodec_initialized = 1;
971 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000972}
973
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000974/* Import the site module (not into __main__ though) */
975
976static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000977initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyObject *m;
980 m = PyImport_ImportModule("site");
981 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200982 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyErr_Print();
984 Py_Finalize();
985 exit(1);
986 }
987 else {
988 Py_DECREF(m);
989 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000990}
991
Antoine Pitrou05608432009-01-09 18:53:14 +0000992static PyObject*
993create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 int fd, int write_mode, char* name,
995 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
998 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000999 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyObject *line_buffering;
1001 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001002 _Py_IDENTIFIER(open);
1003 _Py_IDENTIFIER(isatty);
1004 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001005 _Py_IDENTIFIER(name);
1006 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* stdin is always opened in buffered mode, first because it shouldn't
1009 make a difference in common use cases, second because TextIOWrapper
1010 depends on the presence of a read1() method which only exists on
1011 buffered streams.
1012 */
1013 if (Py_UnbufferedStdioFlag && write_mode)
1014 buffering = 0;
1015 else
1016 buffering = -1;
1017 if (write_mode)
1018 mode = "wb";
1019 else
1020 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001021 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1022 fd, mode, buffering,
1023 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 if (buf == NULL)
1025 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001028 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001029 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (raw == NULL)
1031 goto error;
1032 }
1033 else {
1034 raw = buf;
1035 Py_INCREF(raw);
1036 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001039 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001041 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 if (res == NULL)
1043 goto error;
1044 isatty = PyObject_IsTrue(res);
1045 Py_DECREF(res);
1046 if (isatty == -1)
1047 goto error;
1048 if (isatty || Py_UnbufferedStdioFlag)
1049 line_buffering = Py_True;
1050 else
1051 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 Py_CLEAR(raw);
1054 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001055
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001056#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001057 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1058 newlines to "\n".
1059 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1060 newline = NULL;
1061#else
1062 /* sys.stdin: split lines at "\n".
1063 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1064 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001065#endif
1066
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001067 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1068 buf, encoding, errors,
1069 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 Py_CLEAR(buf);
1071 if (stream == NULL)
1072 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 if (write_mode)
1075 mode = "w";
1076 else
1077 mode = "r";
1078 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001079 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 goto error;
1081 Py_CLEAR(text);
1082 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001083
1084error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 Py_XDECREF(buf);
1086 Py_XDECREF(stream);
1087 Py_XDECREF(text);
1088 Py_XDECREF(raw);
1089 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001090}
1091
Antoine Pitrou11942a52011-11-28 19:08:36 +01001092static int
1093is_valid_fd(int fd)
1094{
1095 int dummy_fd;
1096 if (fd < 0 || !_PyVerify_fd(fd))
1097 return 0;
1098 dummy_fd = dup(fd);
1099 if (dummy_fd < 0)
1100 return 0;
1101 close(dummy_fd);
1102 return 1;
1103}
1104
Georg Brandl1a3284e2007-12-02 09:40:06 +00001105/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001106static int
1107initstdio(void)
1108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 PyObject *iomod = NULL, *wrapper;
1110 PyObject *bimod = NULL;
1111 PyObject *m;
1112 PyObject *std = NULL;
1113 int status = 0, fd;
1114 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001115 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 /* Hack to avoid a nasty recursion issue when Python is invoked
1118 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1119 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1120 goto error;
1121 }
1122 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1125 goto error;
1126 }
1127 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 if (!(bimod = PyImport_ImportModule("builtins"))) {
1130 goto error;
1131 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 if (!(iomod = PyImport_ImportModule("io"))) {
1134 goto error;
1135 }
1136 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1137 goto error;
1138 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 /* Set builtins.open */
1141 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001142 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 goto error;
1144 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001145 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001146
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001147 encoding = _Py_StandardStreamEncoding;
1148 errors = _Py_StandardStreamErrors;
1149 if (!encoding || !errors) {
1150 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1151 if (pythonioencoding) {
1152 char *err;
1153 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1154 if (pythonioencoding == NULL) {
1155 PyErr_NoMemory();
1156 goto error;
1157 }
1158 err = strchr(pythonioencoding, ':');
1159 if (err) {
1160 *err = '\0';
1161 err++;
1162 if (*err && !errors) {
1163 errors = err;
1164 }
1165 }
1166 if (*pythonioencoding && !encoding) {
1167 encoding = pythonioencoding;
1168 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001169 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 /* Set sys.stdin */
1173 fd = fileno(stdin);
1174 /* Under some conditions stdin, stdout and stderr may not be connected
1175 * and fileno() may point to an invalid file descriptor. For example
1176 * GUI apps don't have valid standard streams by default.
1177 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001178 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 std = Py_None;
1180 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 }
1182 else {
1183 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1184 if (std == NULL)
1185 goto error;
1186 } /* if (fd < 0) */
1187 PySys_SetObject("__stdin__", std);
Victor Stinner09054372013-11-06 22:41:44 +01001188 _PySys_SetObjectId(&_PyId_stdin, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 /* Set sys.stdout */
1192 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001193 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 std = Py_None;
1195 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 }
1197 else {
1198 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1199 if (std == NULL)
1200 goto error;
1201 } /* if (fd < 0) */
1202 PySys_SetObject("__stdout__", std);
Victor Stinner09054372013-11-06 22:41:44 +01001203 _PySys_SetObjectId(&_PyId_stdout, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001205
Guido van Rossum98297ee2007-11-06 21:34:58 +00001206#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 /* Set sys.stderr, replaces the preliminary stderr */
1208 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001209 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 std = Py_None;
1211 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 }
1213 else {
1214 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1215 if (std == NULL)
1216 goto error;
1217 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 /* Same as hack above, pre-import stderr's codec to avoid recursion
1220 when import.c tries to write to stderr in verbose mode. */
1221 encoding_attr = PyObject_GetAttrString(std, "encoding");
1222 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001223 const char * std_encoding;
1224 std_encoding = _PyUnicode_AsString(encoding_attr);
1225 if (std_encoding != NULL) {
1226 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001227 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001229 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 }
1231 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001232
Victor Stinnerba308832013-07-22 23:55:19 +02001233 if (PySys_SetObject("__stderr__", std) < 0) {
1234 Py_DECREF(std);
1235 goto error;
1236 }
Victor Stinner09054372013-11-06 22:41:44 +01001237 if (_PySys_SetObjectId(&_PyId_stderr, std) < 0) {
Victor Stinnerba308832013-07-22 23:55:19 +02001238 Py_DECREF(std);
1239 goto error;
1240 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001242#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001245 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 status = -1;
1247 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001248
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001249 /* We won't need them anymore. */
1250 if (_Py_StandardStreamEncoding) {
1251 PyMem_RawFree(_Py_StandardStreamEncoding);
1252 _Py_StandardStreamEncoding = NULL;
1253 }
1254 if (_Py_StandardStreamErrors) {
1255 PyMem_RawFree(_Py_StandardStreamErrors);
1256 _Py_StandardStreamErrors = NULL;
1257 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001258 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 Py_XDECREF(bimod);
1260 Py_XDECREF(iomod);
1261 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001262}
1263
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001264/* Parse input from a file and execute it */
1265
1266int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001267PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 if (filename == NULL)
1271 filename = "???";
1272 if (Py_FdIsInteractive(fp, filename)) {
1273 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1274 if (closeit)
1275 fclose(fp);
1276 return err;
1277 }
1278 else
1279 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001280}
1281
1282int
Victor Stinner95701bd2013-11-06 18:41:07 +01001283PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001284{
Victor Stinner95701bd2013-11-06 18:41:07 +01001285 PyObject *filename, *v;
1286 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001288
Victor Stinner95701bd2013-11-06 18:41:07 +01001289 filename = PyUnicode_DecodeFSDefault(filename_str);
1290 if (filename == NULL) {
1291 PyErr_Print();
1292 return -1;
1293 }
1294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 if (flags == NULL) {
1296 flags = &local_flags;
1297 local_flags.cf_flags = 0;
1298 }
Victor Stinner09054372013-11-06 22:41:44 +01001299 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001301 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 Py_XDECREF(v);
1303 }
Victor Stinner09054372013-11-06 22:41:44 +01001304 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001306 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 Py_XDECREF(v);
1308 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001309 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 for (;;) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001311 ret = PyRun_InteractiveOneObject(fp, filename, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 PRINT_TOTAL_REFS();
Victor Stinner95701bd2013-11-06 18:41:07 +01001313 if (ret == E_EOF) {
1314 err = 0;
1315 break;
1316 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 /*
1318 if (ret == E_NOMEM)
Victor Stinner95701bd2013-11-06 18:41:07 +01001319 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 */
1321 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001322 Py_DECREF(filename);
1323 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001324}
1325
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001326/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001327static int PARSER_FLAGS(PyCompilerFlags *flags)
1328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 int parser_flags = 0;
1330 if (!flags)
1331 return 0;
1332 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1333 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1334 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1335 parser_flags |= PyPARSE_IGNORE_COOKIE;
1336 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1337 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1338 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001339}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001340
Thomas Wouters89f507f2006-12-13 04:49:30 +00001341#if 0
1342/* Keep an example of flags with future keyword support. */
1343#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1345 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1346 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1347 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001348#endif
1349
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001350int
Victor Stinner95701bd2013-11-06 18:41:07 +01001351PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001352{
Victor Stinner95701bd2013-11-06 18:41:07 +01001353 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 mod_ty mod;
1355 PyArena *arena;
1356 char *ps1 = "", *ps2 = "", *enc = NULL;
1357 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001358 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +01001359 _Py_IDENTIFIER(__main__);
1360
1361 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
1362 if (mod_name == NULL) {
1363 PyErr_Print();
1364 return -1;
1365 }
Tim Petersfe2127d2001-07-16 05:37:24 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001368 /* Fetch encoding from sys.stdin if possible. */
Victor Stinner09054372013-11-06 22:41:44 +01001369 v = _PySys_GetObjectId(&_PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001370 if (v && v != Py_None) {
1371 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1372 if (oenc)
1373 enc = _PyUnicode_AsString(oenc);
1374 if (!enc)
1375 PyErr_Clear();
1376 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 }
Victor Stinner09054372013-11-06 22:41:44 +01001378 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 if (v != NULL) {
1380 v = PyObject_Str(v);
1381 if (v == NULL)
1382 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001383 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001385 if (ps1 == NULL) {
1386 PyErr_Clear();
1387 ps1 = "";
1388 }
1389 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 }
Victor Stinner09054372013-11-06 22:41:44 +01001391 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 if (w != NULL) {
1393 w = PyObject_Str(w);
1394 if (w == NULL)
1395 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001396 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001398 if (ps2 == NULL) {
1399 PyErr_Clear();
1400 ps2 = "";
1401 }
1402 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 }
1404 arena = PyArena_New();
1405 if (arena == NULL) {
1406 Py_XDECREF(v);
1407 Py_XDECREF(w);
1408 Py_XDECREF(oenc);
1409 return -1;
1410 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001411 mod = PyParser_ASTFromFileObject(fp, filename, enc,
1412 Py_single_input, ps1, ps2,
1413 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 Py_XDECREF(v);
1415 Py_XDECREF(w);
1416 Py_XDECREF(oenc);
1417 if (mod == NULL) {
1418 PyArena_Free(arena);
1419 if (errcode == E_EOF) {
1420 PyErr_Clear();
1421 return E_EOF;
1422 }
1423 PyErr_Print();
1424 return -1;
1425 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001426 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 if (m == NULL) {
1428 PyArena_Free(arena);
1429 return -1;
1430 }
1431 d = PyModule_GetDict(m);
1432 v = run_mod(mod, filename, d, d, flags, arena);
1433 PyArena_Free(arena);
1434 flush_io();
1435 if (v == NULL) {
1436 PyErr_Print();
1437 return -1;
1438 }
1439 Py_DECREF(v);
1440 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001441}
1442
Victor Stinner95701bd2013-11-06 18:41:07 +01001443int
1444PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
1445{
1446 PyObject *filename;
1447 int res;
1448
1449 filename = PyUnicode_DecodeFSDefault(filename_str);
1450 if (filename == NULL) {
1451 PyErr_Print();
1452 return -1;
1453 }
1454 res = PyRun_InteractiveOneObject(fp, filename, flags);
1455 Py_DECREF(filename);
1456 return res;
1457}
1458
1459
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001460/* Check whether a file maybe a pyc file: Look at the extension,
1461 the file type, and, if we may close it, at the first few bytes. */
1462
1463static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001464maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1467 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 /* Only look into the file if we are allowed to close it, since
1470 it then should also be seekable. */
1471 if (closeit) {
1472 /* Read only two bytes of the magic. If the file was opened in
1473 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1474 be read as they are on disk. */
1475 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1476 unsigned char buf[2];
1477 /* Mess: In case of -x, the stream is NOT at its start now,
1478 and ungetc() was used to push back the first newline,
1479 which makes the current stream position formally undefined,
1480 and a x-platform nightmare.
1481 Unfortunately, we have no direct way to know whether -x
1482 was specified. So we use a terrible hack: if the current
1483 stream position is not 0, we assume -x was specified, and
1484 give up. Bug 132850 on SourceForge spells out the
1485 hopelessness of trying anything else (fseek and ftell
1486 don't work predictably x-platform for text-mode files).
1487 */
1488 int ispyc = 0;
1489 if (ftell(fp) == 0) {
1490 if (fread(buf, 1, 2, fp) == 2 &&
1491 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1492 ispyc = 1;
1493 rewind(fp);
1494 }
1495 return ispyc;
1496 }
1497 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001498}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001499
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001500static int
1501set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001502{
1503 PyInterpreterState *interp;
1504 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001505 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001506 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001507
1508 filename_obj = PyUnicode_DecodeFSDefault(filename);
1509 if (filename_obj == NULL)
1510 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001511 /* Get current thread state and interpreter pointer */
1512 tstate = PyThreadState_GET();
1513 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001514 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1515 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001516 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001517 return -1;
1518 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001519 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001520 Py_DECREF(loader_type);
1521 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001522 return -1;
1523 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001524 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1525 result = -1;
1526 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001527 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001528 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001529}
1530
1531int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001532PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 PyObject *m, *d, *v;
1536 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001537 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001538 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 m = PyImport_AddModule("__main__");
1541 if (m == NULL)
1542 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001543 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 d = PyModule_GetDict(m);
1545 if (PyDict_GetItemString(d, "__file__") == NULL) {
1546 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001547 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001549 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1551 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001552 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001554 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1555 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001556 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001557 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 set_file_name = 1;
1559 Py_DECREF(f);
1560 }
1561 len = strlen(filename);
1562 ext = filename + len - (len > 4 ? 4 : 0);
1563 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001564 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 /* Try to run a pyc file. First, re-open in binary */
1566 if (closeit)
1567 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001568 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 goto done;
1571 }
1572 /* Turn on optimization if a .pyo file is given */
1573 if (strcmp(ext, ".pyo") == 0)
1574 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001575
1576 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1577 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1578 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001579 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001580 goto done;
1581 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001582 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1583 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001584 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001585 /* When running from stdin, leave __main__.__loader__ alone */
1586 if (strcmp(filename, "<stdin>") != 0 &&
1587 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1588 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1589 ret = -1;
1590 goto done;
1591 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1593 closeit, flags);
1594 }
1595 flush_io();
1596 if (v == NULL) {
1597 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 goto done;
1599 }
1600 Py_DECREF(v);
1601 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001602 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1604 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001605 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001607}
1608
1609int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001610PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 PyObject *m, *d, *v;
1613 m = PyImport_AddModule("__main__");
1614 if (m == NULL)
1615 return -1;
1616 d = PyModule_GetDict(m);
1617 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1618 if (v == NULL) {
1619 PyErr_Print();
1620 return -1;
1621 }
1622 Py_DECREF(v);
1623 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001624}
1625
Barry Warsaw035574d1997-08-29 22:07:17 +00001626static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001627parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 long hold;
1631 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001632 _Py_IDENTIFIER(msg);
1633 _Py_IDENTIFIER(filename);
1634 _Py_IDENTIFIER(lineno);
1635 _Py_IDENTIFIER(offset);
1636 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001637
Benjamin Peterson80d50422012-04-03 00:30:38 -04001638 *message = NULL;
1639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001641 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001642 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001644
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001645 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001646 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001648 if (v == Py_None) {
1649 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001651 }
1652 else {
1653 *filename = _PyUnicode_AsString(v);
1654 Py_DECREF(v);
1655 if (!*filename)
1656 goto finally;
1657 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001658
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001659 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001660 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 goto finally;
1662 hold = PyLong_AsLong(v);
1663 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 if (hold < 0 && PyErr_Occurred())
1665 goto finally;
1666 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001667
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001668 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001669 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 goto finally;
1671 if (v == Py_None) {
1672 *offset = -1;
1673 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 } else {
1675 hold = PyLong_AsLong(v);
1676 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 if (hold < 0 && PyErr_Occurred())
1678 goto finally;
1679 *offset = (int)hold;
1680 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001681
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001682 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001683 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001685 if (v == Py_None) {
1686 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001688 }
1689 else {
1690 *text = _PyUnicode_AsString(v);
1691 Py_DECREF(v);
1692 if (!*text)
1693 goto finally;
1694 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001696
1697finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001698 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001700}
1701
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001702void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001703PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001706}
1707
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001708static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001709print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 char *nl;
1712 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001713 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1714 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 for (;;) {
1716 nl = strchr(text, '\n');
1717 if (nl == NULL || nl-text >= offset)
1718 break;
1719 offset -= (int)(nl+1-text);
1720 text = nl+1;
1721 }
1722 while (*text == ' ' || *text == '\t') {
1723 text++;
1724 offset--;
1725 }
1726 }
1727 PyFile_WriteString(" ", f);
1728 PyFile_WriteString(text, f);
1729 if (*text == '\0' || text[strlen(text)-1] != '\n')
1730 PyFile_WriteString("\n", f);
1731 if (offset == -1)
1732 return;
1733 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001734 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001737}
1738
Guido van Rossum66e8e862001-03-23 17:54:43 +00001739static void
1740handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 PyObject *exception, *value, *tb;
1743 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (Py_InspectFlag)
1746 /* Don't exit if -i flag was given. This flag is set to 0
1747 * when entering interactive mode for inspecting. */
1748 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 PyErr_Fetch(&exception, &value, &tb);
1751 fflush(stdout);
1752 if (value == NULL || value == Py_None)
1753 goto done;
1754 if (PyExceptionInstance_Check(value)) {
1755 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001756 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001757 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 if (code) {
1759 Py_DECREF(value);
1760 value = code;
1761 if (value == Py_None)
1762 goto done;
1763 }
1764 /* If we failed to dig out the 'code' attribute,
1765 just let the else clause below print the error. */
1766 }
1767 if (PyLong_Check(value))
1768 exitcode = (int)PyLong_AsLong(value);
1769 else {
Victor Stinner09054372013-11-06 22:41:44 +01001770 PyObject *sys_stderr = _PySys_GetObjectId(&_PyId_stderr);
Victor Stinner7126dbc2010-05-21 23:45:42 +00001771 if (sys_stderr != NULL && sys_stderr != Py_None) {
1772 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1773 } else {
1774 PyObject_Print(value, stderr, Py_PRINT_RAW);
1775 fflush(stderr);
1776 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 PySys_WriteStderr("\n");
1778 exitcode = 1;
1779 }
Tim Peterscf615b52003-04-19 18:47:02 +00001780 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 /* Restore and clear the exception info, in order to properly decref
1782 * the exception, value, and traceback. If we just exit instead,
1783 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1784 * some finalizers from running.
1785 */
1786 PyErr_Restore(exception, value, tb);
1787 PyErr_Clear();
1788 Py_Exit(exitcode);
1789 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001790}
1791
1792void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001793PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1798 handle_system_exit();
1799 }
1800 PyErr_Fetch(&exception, &v, &tb);
1801 if (exception == NULL)
1802 return;
1803 PyErr_NormalizeException(&exception, &v, &tb);
1804 if (tb == NULL) {
1805 tb = Py_None;
1806 Py_INCREF(tb);
1807 }
1808 PyException_SetTraceback(v, tb);
1809 if (exception == NULL)
1810 return;
1811 /* Now we know v != NULL too */
1812 if (set_sys_last_vars) {
Victor Stinner09054372013-11-06 22:41:44 +01001813 _PySys_SetObjectId(&PyId_last_type, exception);
1814 _PySys_SetObjectId(&PyId_last_value, v);
1815 _PySys_SetObjectId(&PyId_last_traceback, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 }
Victor Stinner09054372013-11-06 22:41:44 +01001817 hook = _PySys_GetObjectId(&PyId_excepthook);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (hook) {
1819 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1820 PyObject *result = PyEval_CallObject(hook, args);
1821 if (result == NULL) {
1822 PyObject *exception2, *v2, *tb2;
1823 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1824 handle_system_exit();
1825 }
1826 PyErr_Fetch(&exception2, &v2, &tb2);
1827 PyErr_NormalizeException(&exception2, &v2, &tb2);
1828 /* It should not be possible for exception2 or v2
1829 to be NULL. However PyErr_Display() can't
1830 tolerate NULLs, so just be safe. */
1831 if (exception2 == NULL) {
1832 exception2 = Py_None;
1833 Py_INCREF(exception2);
1834 }
1835 if (v2 == NULL) {
1836 v2 = Py_None;
1837 Py_INCREF(v2);
1838 }
1839 fflush(stdout);
1840 PySys_WriteStderr("Error in sys.excepthook:\n");
1841 PyErr_Display(exception2, v2, tb2);
1842 PySys_WriteStderr("\nOriginal exception was:\n");
1843 PyErr_Display(exception, v, tb);
1844 Py_DECREF(exception2);
1845 Py_DECREF(v2);
1846 Py_XDECREF(tb2);
1847 }
1848 Py_XDECREF(result);
1849 Py_XDECREF(args);
1850 } else {
1851 PySys_WriteStderr("sys.excepthook is missing\n");
1852 PyErr_Display(exception, v, tb);
1853 }
1854 Py_XDECREF(exception);
1855 Py_XDECREF(v);
1856 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001857}
1858
Benjamin Petersone6528212008-07-15 15:32:09 +00001859static void
1860print_exception(PyObject *f, PyObject *value)
1861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 int err = 0;
1863 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001864 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 if (!PyExceptionInstance_Check(value)) {
1867 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1868 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1869 PyFile_WriteString(" found\n", f);
1870 return;
1871 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 Py_INCREF(value);
1874 fflush(stdout);
1875 type = (PyObject *) Py_TYPE(value);
1876 tb = PyException_GetTraceback(value);
1877 if (tb && tb != Py_None)
1878 err = PyTraceBack_Print(tb, f);
1879 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001880 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 {
1882 PyObject *message;
1883 const char *filename, *text;
1884 int lineno, offset;
1885 if (!parse_syntax_error(value, &message, &filename,
1886 &lineno, &offset, &text))
1887 PyErr_Clear();
1888 else {
1889 char buf[10];
1890 PyFile_WriteString(" File \"", f);
1891 if (filename == NULL)
1892 PyFile_WriteString("<string>", f);
1893 else
1894 PyFile_WriteString(filename, f);
1895 PyFile_WriteString("\", line ", f);
1896 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1897 PyFile_WriteString(buf, f);
1898 PyFile_WriteString("\n", f);
1899 if (text != NULL)
1900 print_error_text(f, offset, text);
1901 Py_DECREF(value);
1902 value = message;
1903 /* Can't be bothered to check all those
1904 PyFile_WriteString() calls */
1905 if (PyErr_Occurred())
1906 err = -1;
1907 }
1908 }
1909 if (err) {
1910 /* Don't do anything else */
1911 }
1912 else {
1913 PyObject* moduleName;
1914 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001915 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 assert(PyExceptionClass_Check(type));
1917 className = PyExceptionClass_Name(type);
1918 if (className != NULL) {
1919 char *dot = strrchr(className, '.');
1920 if (dot != NULL)
1921 className = dot+1;
1922 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001923
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001924 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1926 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001927 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 err = PyFile_WriteString("<unknown>", f);
1929 }
1930 else {
1931 char* modstr = _PyUnicode_AsString(moduleName);
1932 if (modstr && strcmp(modstr, "builtins"))
1933 {
1934 err = PyFile_WriteString(modstr, f);
1935 err += PyFile_WriteString(".", f);
1936 }
1937 Py_DECREF(moduleName);
1938 }
1939 if (err == 0) {
1940 if (className == NULL)
1941 err = PyFile_WriteString("<unknown>", f);
1942 else
1943 err = PyFile_WriteString(className, f);
1944 }
1945 }
1946 if (err == 0 && (value != Py_None)) {
1947 PyObject *s = PyObject_Str(value);
1948 /* only print colon if the str() of the
1949 object is not the empty string
1950 */
1951 if (s == NULL)
1952 err = -1;
1953 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001954 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 err = PyFile_WriteString(": ", f);
1956 if (err == 0)
1957 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1958 Py_XDECREF(s);
1959 }
1960 /* try to write a newline in any case */
1961 err += PyFile_WriteString("\n", f);
1962 Py_XDECREF(tb);
1963 Py_DECREF(value);
1964 /* If an error happened here, don't show it.
1965 XXX This is wrong, but too many callers rely on this behavior. */
1966 if (err != 0)
1967 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001968}
1969
1970static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 "\nThe above exception was the direct cause "
1972 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001973
1974static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 "\nDuring handling of the above exception, "
1976 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001977
1978static void
1979print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 int err = 0, res;
1982 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 if (seen != NULL) {
1985 /* Exception chaining */
1986 if (PySet_Add(seen, value) == -1)
1987 PyErr_Clear();
1988 else if (PyExceptionInstance_Check(value)) {
1989 cause = PyException_GetCause(value);
1990 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001991 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 res = PySet_Contains(seen, cause);
1993 if (res == -1)
1994 PyErr_Clear();
1995 if (res == 0) {
1996 print_exception_recursive(
1997 f, cause, seen);
1998 err |= PyFile_WriteString(
1999 cause_message, f);
2000 }
2001 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002002 else if (context &&
2003 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 res = PySet_Contains(seen, context);
2005 if (res == -1)
2006 PyErr_Clear();
2007 if (res == 0) {
2008 print_exception_recursive(
2009 f, context, seen);
2010 err |= PyFile_WriteString(
2011 context_message, f);
2012 }
2013 }
2014 Py_XDECREF(context);
2015 Py_XDECREF(cause);
2016 }
2017 }
2018 print_exception(f, value);
2019 if (err != 0)
2020 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002021}
2022
Thomas Wouters477c8d52006-05-27 19:21:47 +00002023void
2024PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 PyObject *seen;
Victor Stinner09054372013-11-06 22:41:44 +01002027 PyObject *f = _PySys_GetObjectId(&_PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +02002028 if (PyExceptionInstance_Check(value)
2029 && tb != NULL && PyTraceBack_Check(tb)) {
2030 /* Put the traceback on the exception, otherwise it won't get
2031 displayed. See issue #18776. */
2032 PyObject *cur_tb = PyException_GetTraceback(value);
2033 if (cur_tb == NULL)
2034 PyException_SetTraceback(value, tb);
2035 else
2036 Py_DECREF(cur_tb);
2037 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 if (f == Py_None) {
2039 /* pass */
2040 }
2041 else if (f == NULL) {
2042 _PyObject_Dump(value);
2043 fprintf(stderr, "lost sys.stderr\n");
2044 }
2045 else {
2046 /* We choose to ignore seen being possibly NULL, and report
2047 at least the main exception (it could be a MemoryError).
2048 */
2049 seen = PySet_New(NULL);
2050 if (seen == NULL)
2051 PyErr_Clear();
2052 print_exception_recursive(f, value, seen);
2053 Py_XDECREF(seen);
2054 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002055}
2056
Guido van Rossum82598051997-03-05 00:20:32 +00002057PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002058PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 PyObject *ret = NULL;
2062 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002063 PyArena *arena;
2064 _Py_static_string(PyId_string, "<string>");
2065 PyObject *filename;
2066
2067 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2068 if (filename == NULL)
2069 return NULL;
2070
2071 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 if (arena == NULL)
2073 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002074
Victor Stinner95701bd2013-11-06 18:41:07 +01002075 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002077 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 PyArena_Free(arena);
2079 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002080}
2081
2082PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002083PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002085{
Victor Stinner95701bd2013-11-06 18:41:07 +01002086 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002088 PyArena *arena = NULL;
2089 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002090
Victor Stinner95701bd2013-11-06 18:41:07 +01002091 filename = PyUnicode_DecodeFSDefault(filename_str);
2092 if (filename == NULL)
2093 goto exit;
2094
2095 arena = PyArena_New();
2096 if (arena == NULL)
2097 goto exit;
2098
2099 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2100 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 if (closeit)
2102 fclose(fp);
2103 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002104 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 }
2106 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002107
2108exit:
2109 Py_XDECREF(filename);
2110 if (arena != NULL)
2111 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002113}
2114
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002115static void
2116flush_io(void)
2117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 PyObject *f, *r;
2119 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002120 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 /* Save the current exception */
2123 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002124
Victor Stinner09054372013-11-06 22:41:44 +01002125 f = _PySys_GetObjectId(&_PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002127 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 if (r)
2129 Py_DECREF(r);
2130 else
2131 PyErr_Clear();
2132 }
Victor Stinner09054372013-11-06 22:41:44 +01002133 f = _PySys_GetObjectId(&_PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002135 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 if (r)
2137 Py_DECREF(r);
2138 else
2139 PyErr_Clear();
2140 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002143}
2144
Guido van Rossum82598051997-03-05 00:20:32 +00002145static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002146run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2147 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 PyCodeObject *co;
2150 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002151 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 if (co == NULL)
2153 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002154 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 Py_DECREF(co);
2156 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002157}
2158
Guido van Rossum82598051997-03-05 00:20:32 +00002159static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002160run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 PyCodeObject *co;
2164 PyObject *v;
2165 long magic;
2166 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 magic = PyMarshal_ReadLongFromFile(fp);
2169 if (magic != PyImport_GetMagicNumber()) {
2170 PyErr_SetString(PyExc_RuntimeError,
2171 "Bad magic number in .pyc file");
2172 return NULL;
2173 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002174 /* Skip mtime and size */
2175 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 (void) PyMarshal_ReadLongFromFile(fp);
2177 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 if (v == NULL || !PyCode_Check(v)) {
2179 Py_XDECREF(v);
2180 PyErr_SetString(PyExc_RuntimeError,
2181 "Bad code object in .pyc file");
2182 return NULL;
2183 }
2184 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002185 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 if (v && flags)
2187 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2188 Py_DECREF(co);
2189 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002190}
2191
Guido van Rossum82598051997-03-05 00:20:32 +00002192PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002193Py_CompileStringObject(const char *str, PyObject *filename, int start,
2194 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 PyCodeObject *co;
2197 mod_ty mod;
2198 PyArena *arena = PyArena_New();
2199 if (arena == NULL)
2200 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002201
Victor Stinner14e461d2013-08-26 22:28:21 +02002202 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 if (mod == NULL) {
2204 PyArena_Free(arena);
2205 return NULL;
2206 }
2207 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2208 PyObject *result = PyAST_mod2obj(mod);
2209 PyArena_Free(arena);
2210 return result;
2211 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002212 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 PyArena_Free(arena);
2214 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002215}
2216
Victor Stinner14e461d2013-08-26 22:28:21 +02002217PyObject *
2218Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2219 PyCompilerFlags *flags, int optimize)
2220{
2221 PyObject *filename, *co;
2222 filename = PyUnicode_DecodeFSDefault(filename_str);
2223 if (filename == NULL)
2224 return NULL;
2225 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2226 Py_DECREF(filename);
2227 return co;
2228}
2229
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002230/* For use in Py_LIMITED_API */
2231#undef Py_CompileString
2232PyObject *
2233PyCompileString(const char *str, const char *filename, int start)
2234{
2235 return Py_CompileStringFlags(str, filename, start, NULL);
2236}
2237
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002238struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002239Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 struct symtable *st;
2242 mod_ty mod;
2243 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002244 PyArena *arena;
2245
2246 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (arena == NULL)
2248 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002251 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 if (mod == NULL) {
2253 PyArena_Free(arena);
2254 return NULL;
2255 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002256 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 PyArena_Free(arena);
2258 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002259}
2260
Victor Stinner14e461d2013-08-26 22:28:21 +02002261struct symtable *
2262Py_SymtableString(const char *str, const char *filename_str, int start)
2263{
2264 PyObject *filename;
2265 struct symtable *st;
2266
2267 filename = PyUnicode_DecodeFSDefault(filename_str);
2268 if (filename == NULL)
2269 return NULL;
2270 st = Py_SymtableStringObject(str, filename, start);
2271 Py_DECREF(filename);
2272 return st;
2273}
2274
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002275/* Preferred access to parser is through AST. */
2276mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002277PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2278 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 mod_ty mod;
2281 PyCompilerFlags localflags;
2282 perrdetail err;
2283 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002284
Victor Stinner14e461d2013-08-26 22:28:21 +02002285 node *n = PyParser_ParseStringObject(s, filename,
2286 &_PyParser_Grammar, start, &err,
2287 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 if (flags == NULL) {
2289 localflags.cf_flags = 0;
2290 flags = &localflags;
2291 }
2292 if (n) {
2293 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002294 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 }
2297 else {
2298 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002299 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002301 err_free(&err);
2302 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002303}
2304
2305mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002306PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2307 PyCompilerFlags *flags, PyArena *arena)
2308{
2309 PyObject *filename;
2310 mod_ty mod;
2311 filename = PyUnicode_DecodeFSDefault(filename_str);
2312 if (filename == NULL)
2313 return NULL;
2314 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2315 Py_DECREF(filename);
2316 return mod;
2317}
2318
2319mod_ty
2320PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2321 int start, char *ps1,
2322 char *ps2, PyCompilerFlags *flags, int *errcode,
2323 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 mod_ty mod;
2326 PyCompilerFlags localflags;
2327 perrdetail err;
2328 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002329
Victor Stinner14e461d2013-08-26 22:28:21 +02002330 node *n = PyParser_ParseFileObject(fp, filename, enc,
2331 &_PyParser_Grammar,
2332 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 if (flags == NULL) {
2334 localflags.cf_flags = 0;
2335 flags = &localflags;
2336 }
2337 if (n) {
2338 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002339 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 }
2342 else {
2343 err_input(&err);
2344 if (errcode)
2345 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002346 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002348 err_free(&err);
2349 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002350}
2351
Victor Stinner14e461d2013-08-26 22:28:21 +02002352mod_ty
2353PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2354 int start, char *ps1,
2355 char *ps2, PyCompilerFlags *flags, int *errcode,
2356 PyArena *arena)
2357{
2358 mod_ty mod;
2359 PyObject *filename;
2360 filename = PyUnicode_DecodeFSDefault(filename_str);
2361 if (filename == NULL)
2362 return NULL;
2363 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2364 flags, errcode, arena);
2365 Py_DECREF(filename);
2366 return mod;
2367}
2368
Guido van Rossuma110aa61994-08-29 12:50:44 +00002369/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002370
Guido van Rossuma110aa61994-08-29 12:50:44 +00002371node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002372PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 perrdetail err;
2375 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2376 &_PyParser_Grammar,
2377 start, NULL, NULL, &err, flags);
2378 if (n == NULL)
2379 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002380 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002383}
2384
Guido van Rossuma110aa61994-08-29 12:50:44 +00002385/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002386
Guido van Rossuma110aa61994-08-29 12:50:44 +00002387node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002388PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 perrdetail err;
2391 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2392 start, &err, flags);
2393 if (n == NULL)
2394 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002395 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002397}
2398
2399node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002400PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 perrdetail err;
2404 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2405 &_PyParser_Grammar, start, &err, flags);
2406 if (n == NULL)
2407 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002408 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002410}
2411
2412node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002413PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002416}
2417
Guido van Rossum66ebd912003-04-17 16:02:26 +00002418/* May want to move a more generalized form of this to parsetok.c or
2419 even parser modules. */
2420
2421void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002422PyParser_ClearError(perrdetail *err)
2423{
2424 err_free(err);
2425}
2426
2427void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002428PyParser_SetError(perrdetail *err)
2429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002431}
2432
Victor Stinner7f2fee32011-04-05 00:39:01 +02002433static void
2434err_free(perrdetail *err)
2435{
2436 Py_CLEAR(err->filename);
2437}
2438
Guido van Rossuma110aa61994-08-29 12:50:44 +00002439/* Set the error appropriate to the given input error code (see errcode.h) */
2440
2441static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002442err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 PyObject *v, *w, *errtype, *errtext;
2445 PyObject *msg_obj = NULL;
2446 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 errtype = PyExc_SyntaxError;
2449 switch (err->error) {
2450 case E_ERROR:
2451 return;
2452 case E_SYNTAX:
2453 errtype = PyExc_IndentationError;
2454 if (err->expected == INDENT)
2455 msg = "expected an indented block";
2456 else if (err->token == INDENT)
2457 msg = "unexpected indent";
2458 else if (err->token == DEDENT)
2459 msg = "unexpected unindent";
2460 else {
2461 errtype = PyExc_SyntaxError;
2462 msg = "invalid syntax";
2463 }
2464 break;
2465 case E_TOKEN:
2466 msg = "invalid token";
2467 break;
2468 case E_EOFS:
2469 msg = "EOF while scanning triple-quoted string literal";
2470 break;
2471 case E_EOLS:
2472 msg = "EOL while scanning string literal";
2473 break;
2474 case E_INTR:
2475 if (!PyErr_Occurred())
2476 PyErr_SetNone(PyExc_KeyboardInterrupt);
2477 goto cleanup;
2478 case E_NOMEM:
2479 PyErr_NoMemory();
2480 goto cleanup;
2481 case E_EOF:
2482 msg = "unexpected EOF while parsing";
2483 break;
2484 case E_TABSPACE:
2485 errtype = PyExc_TabError;
2486 msg = "inconsistent use of tabs and spaces in indentation";
2487 break;
2488 case E_OVERFLOW:
2489 msg = "expression too long";
2490 break;
2491 case E_DEDENT:
2492 errtype = PyExc_IndentationError;
2493 msg = "unindent does not match any outer indentation level";
2494 break;
2495 case E_TOODEEP:
2496 errtype = PyExc_IndentationError;
2497 msg = "too many levels of indentation";
2498 break;
2499 case E_DECODE: {
2500 PyObject *type, *value, *tb;
2501 PyErr_Fetch(&type, &value, &tb);
2502 msg = "unknown decode error";
2503 if (value != NULL)
2504 msg_obj = PyObject_Str(value);
2505 Py_XDECREF(type);
2506 Py_XDECREF(value);
2507 Py_XDECREF(tb);
2508 break;
2509 }
2510 case E_LINECONT:
2511 msg = "unexpected character after line continuation character";
2512 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 case E_IDENTIFIER:
2515 msg = "invalid character in identifier";
2516 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002517 case E_BADSINGLE:
2518 msg = "multiple statements found while compiling a single statement";
2519 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 default:
2521 fprintf(stderr, "error=%d\n", err->error);
2522 msg = "unknown parsing error";
2523 break;
2524 }
2525 /* err->text may not be UTF-8 in case of decoding errors.
2526 Explicitly convert to an object. */
2527 if (!err->text) {
2528 errtext = Py_None;
2529 Py_INCREF(Py_None);
2530 } else {
2531 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2532 "replace");
2533 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002534 v = Py_BuildValue("(OiiN)", err->filename,
2535 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (v != NULL) {
2537 if (msg_obj)
2538 w = Py_BuildValue("(OO)", msg_obj, v);
2539 else
2540 w = Py_BuildValue("(sO)", msg, v);
2541 } else
2542 w = NULL;
2543 Py_XDECREF(v);
2544 PyErr_SetObject(errtype, w);
2545 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002546cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 Py_XDECREF(msg_obj);
2548 if (err->text != NULL) {
2549 PyObject_FREE(err->text);
2550 err->text = NULL;
2551 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002552}
2553
2554/* Print fatal error message and abort */
2555
2556void
Tim Peters7c321a82002-07-09 02:57:01 +00002557Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002558{
Victor Stinner024e37a2011-03-31 01:31:06 +02002559 const int fd = fileno(stderr);
2560 PyThreadState *tstate;
2561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 fprintf(stderr, "Fatal Python error: %s\n", msg);
2563 fflush(stderr); /* it helps in Windows debug build */
2564 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002565 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002567 else {
2568 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2569 if (tstate != NULL) {
2570 fputc('\n', stderr);
2571 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002572 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002573 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002574 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002575 }
2576
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002577#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 {
2579 size_t len = strlen(msg);
2580 WCHAR* buffer;
2581 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002583 /* Convert the message to wchar_t. This uses a simple one-to-one
2584 conversion, assuming that the this error message actually uses ASCII
2585 only. If this ceases to be true, we will have to convert. */
2586 buffer = alloca( (len+1) * (sizeof *buffer));
2587 for( i=0; i<=len; ++i)
2588 buffer[i] = msg[i];
2589 OutputDebugStringW(L"Fatal Python error: ");
2590 OutputDebugStringW(buffer);
2591 OutputDebugStringW(L"\n");
2592 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002593#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002595#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002596#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002598}
2599
2600/* Clean up and exit */
2601
Guido van Rossuma110aa61994-08-29 12:50:44 +00002602#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002603#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002604#endif
2605
Collin Winter670e6922007-03-21 02:57:17 +00002606static void (*pyexitfunc)(void) = NULL;
2607/* For the atexit module. */
2608void _Py_PyAtExit(void (*func)(void))
2609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002611}
2612
2613static void
2614call_py_exitfuncs(void)
2615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 if (pyexitfunc == NULL)
2617 return;
Collin Winter670e6922007-03-21 02:57:17 +00002618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 (*pyexitfunc)();
2620 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002621}
2622
Antoine Pitrou011bd622009-10-20 21:52:47 +00002623/* Wait until threading._shutdown completes, provided
2624 the threading module was imported in the first place.
2625 The shutdown routine will wait until all non-daemon
2626 "threading" threads have completed. */
2627static void
2628wait_for_thread_shutdown(void)
2629{
2630#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002631 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 PyObject *result;
2633 PyThreadState *tstate = PyThreadState_GET();
2634 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2635 "threading");
2636 if (threading == NULL) {
2637 /* threading not imported */
2638 PyErr_Clear();
2639 return;
2640 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002641 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 if (result == NULL) {
2643 PyErr_WriteUnraisable(threading);
2644 }
2645 else {
2646 Py_DECREF(result);
2647 }
2648 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002649#endif
2650}
2651
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002652#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002653static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002654static int nexitfuncs = 0;
2655
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002656int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 if (nexitfuncs >= NEXITFUNCS)
2659 return -1;
2660 exitfuncs[nexitfuncs++] = func;
2661 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002662}
2663
Guido van Rossumcc283f51997-08-05 02:22:03 +00002664static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002665call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 while (nexitfuncs > 0)
2668 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 fflush(stdout);
2671 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002672}
2673
2674void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002675Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002680}
2681
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002682static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002683initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002684{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002685#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002687#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002688#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002690#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002691#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002693#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002695 if (PyErr_Occurred()) {
2696 Py_FatalError("Py_Initialize: can't import signal");
2697 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002698}
2699
Guido van Rossum7433b121997-02-14 19:45:36 +00002700
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002701/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2702 *
2703 * All of the code in this function must only use async-signal-safe functions,
2704 * listed at `man 7 signal` or
2705 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2706 */
2707void
2708_Py_RestoreSignals(void)
2709{
2710#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002712#endif
2713#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002715#endif
2716#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002718#endif
2719}
2720
2721
Guido van Rossum7433b121997-02-14 19:45:36 +00002722/*
2723 * The file descriptor fd is considered ``interactive'' if either
2724 * a) isatty(fd) is TRUE, or
2725 * b) the -i flag was given, and the filename associated with
2726 * the descriptor is NULL or "<stdin>" or "???".
2727 */
2728int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002729Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 if (isatty((int)fileno(fp)))
2732 return 1;
2733 if (!Py_InteractiveFlag)
2734 return 0;
2735 return (filename == NULL) ||
2736 (strcmp(filename, "<stdin>") == 0) ||
2737 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002738}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002739
2740
Tim Petersd08e3822003-04-17 15:24:21 +00002741#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002742#if defined(WIN32) && defined(_MSC_VER)
2743
2744/* Stack checking for Microsoft C */
2745
2746#include <malloc.h>
2747#include <excpt.h>
2748
Fred Drakee8de31c2000-08-31 05:38:39 +00002749/*
2750 * Return non-zero when we run out of memory on the stack; zero otherwise.
2751 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002752int
Fred Drake399739f2000-08-31 05:52:44 +00002753PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 __try {
2756 /* alloca throws a stack overflow exception if there's
2757 not enough space left on the stack */
2758 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2759 return 0;
2760 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2761 EXCEPTION_EXECUTE_HANDLER :
2762 EXCEPTION_CONTINUE_SEARCH) {
2763 int errcode = _resetstkoflw();
2764 if (errcode == 0)
2765 {
2766 Py_FatalError("Could not reset the stack!");
2767 }
2768 }
2769 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002770}
2771
2772#endif /* WIN32 && _MSC_VER */
2773
2774/* Alternate implementations can be added here... */
2775
2776#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002777
2778
2779/* Wrappers around sigaction() or signal(). */
2780
2781PyOS_sighandler_t
2782PyOS_getsig(int sig)
2783{
2784#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 struct sigaction context;
2786 if (sigaction(sig, NULL, &context) == -1)
2787 return SIG_ERR;
2788 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002789#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002791/* Special signal handling for the secure CRT in Visual Studio 2005 */
2792#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 switch (sig) {
2794 /* Only these signals are valid */
2795 case SIGINT:
2796 case SIGILL:
2797 case SIGFPE:
2798 case SIGSEGV:
2799 case SIGTERM:
2800 case SIGBREAK:
2801 case SIGABRT:
2802 break;
2803 /* Don't call signal() with other values or it will assert */
2804 default:
2805 return SIG_ERR;
2806 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002807#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 handler = signal(sig, SIG_IGN);
2809 if (handler != SIG_ERR)
2810 signal(sig, handler);
2811 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002812#endif
2813}
2814
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002815/*
2816 * All of the code in this function must only use async-signal-safe functions,
2817 * listed at `man 7 signal` or
2818 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2819 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002820PyOS_sighandler_t
2821PyOS_setsig(int sig, PyOS_sighandler_t handler)
2822{
2823#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 /* Some code in Modules/signalmodule.c depends on sigaction() being
2825 * used here if HAVE_SIGACTION is defined. Fix that if this code
2826 * changes to invalidate that assumption.
2827 */
2828 struct sigaction context, ocontext;
2829 context.sa_handler = handler;
2830 sigemptyset(&context.sa_mask);
2831 context.sa_flags = 0;
2832 if (sigaction(sig, &context, &ocontext) == -1)
2833 return SIG_ERR;
2834 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002835#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 PyOS_sighandler_t oldhandler;
2837 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002838#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002840#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002842#endif
2843}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844
2845/* Deprecated C API functions still provided for binary compatiblity */
2846
2847#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002848PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002849PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852}
2853
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002854#undef PyParser_SimpleParseString
2855PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002856PyParser_SimpleParseString(const char *str, int start)
2857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002858 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002860
2861#undef PyRun_AnyFile
2862PyAPI_FUNC(int)
2863PyRun_AnyFile(FILE *fp, const char *name)
2864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002865 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002866}
2867
2868#undef PyRun_AnyFileEx
2869PyAPI_FUNC(int)
2870PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002873}
2874
2875#undef PyRun_AnyFileFlags
2876PyAPI_FUNC(int)
2877PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002880}
2881
2882#undef PyRun_File
2883PyAPI_FUNC(PyObject *)
2884PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002887}
2888
2889#undef PyRun_FileEx
2890PyAPI_FUNC(PyObject *)
2891PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002894}
2895
2896#undef PyRun_FileFlags
2897PyAPI_FUNC(PyObject *)
2898PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002900{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002901 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002902}
2903
2904#undef PyRun_SimpleFile
2905PyAPI_FUNC(int)
2906PyRun_SimpleFile(FILE *f, const char *p)
2907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002909}
2910
2911#undef PyRun_SimpleFileEx
2912PyAPI_FUNC(int)
2913PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002916}
2917
2918
2919#undef PyRun_String
2920PyAPI_FUNC(PyObject *)
2921PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002923 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002924}
2925
2926#undef PyRun_SimpleString
2927PyAPI_FUNC(int)
2928PyRun_SimpleString(const char *s)
2929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002931}
2932
2933#undef Py_CompileString
2934PyAPI_FUNC(PyObject *)
2935Py_CompileString(const char *str, const char *p, int s)
2936{
Georg Brandl8334fd92010-12-04 10:26:46 +00002937 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2938}
2939
2940#undef Py_CompileStringFlags
2941PyAPI_FUNC(PyObject *)
2942Py_CompileStringFlags(const char *str, const char *p, int s,
2943 PyCompilerFlags *flags)
2944{
2945 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002946}
2947
2948#undef PyRun_InteractiveOne
2949PyAPI_FUNC(int)
2950PyRun_InteractiveOne(FILE *f, const char *p)
2951{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002953}
2954
2955#undef PyRun_InteractiveLoop
2956PyAPI_FUNC(int)
2957PyRun_InteractiveLoop(FILE *f, const char *p)
2958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002960}
2961
2962#ifdef __cplusplus
2963}
2964#endif