blob: e0c863811a4bb349c3618515f9d1b58ca881f16d [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 {
Victor Stinner937114f2013-11-07 00:12:30 +01001931 if (PyUnicode_CompareWithASCIIString(moduleName, "builtins") != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 {
Victor Stinner937114f2013-11-07 00:12:30 +01001933 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 err += PyFile_WriteString(".", f);
1935 }
1936 Py_DECREF(moduleName);
1937 }
1938 if (err == 0) {
1939 if (className == NULL)
1940 err = PyFile_WriteString("<unknown>", f);
1941 else
1942 err = PyFile_WriteString(className, f);
1943 }
1944 }
1945 if (err == 0 && (value != Py_None)) {
1946 PyObject *s = PyObject_Str(value);
1947 /* only print colon if the str() of the
1948 object is not the empty string
1949 */
1950 if (s == NULL)
1951 err = -1;
1952 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001953 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 err = PyFile_WriteString(": ", f);
1955 if (err == 0)
1956 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1957 Py_XDECREF(s);
1958 }
1959 /* try to write a newline in any case */
1960 err += PyFile_WriteString("\n", f);
1961 Py_XDECREF(tb);
1962 Py_DECREF(value);
1963 /* If an error happened here, don't show it.
1964 XXX This is wrong, but too many callers rely on this behavior. */
1965 if (err != 0)
1966 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001967}
1968
1969static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 "\nThe above exception was the direct cause "
1971 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001972
1973static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 "\nDuring handling of the above exception, "
1975 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001976
1977static void
1978print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 int err = 0, res;
1981 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 if (seen != NULL) {
1984 /* Exception chaining */
1985 if (PySet_Add(seen, value) == -1)
1986 PyErr_Clear();
1987 else if (PyExceptionInstance_Check(value)) {
1988 cause = PyException_GetCause(value);
1989 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001990 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 res = PySet_Contains(seen, cause);
1992 if (res == -1)
1993 PyErr_Clear();
1994 if (res == 0) {
1995 print_exception_recursive(
1996 f, cause, seen);
1997 err |= PyFile_WriteString(
1998 cause_message, f);
1999 }
2000 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002001 else if (context &&
2002 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 res = PySet_Contains(seen, context);
2004 if (res == -1)
2005 PyErr_Clear();
2006 if (res == 0) {
2007 print_exception_recursive(
2008 f, context, seen);
2009 err |= PyFile_WriteString(
2010 context_message, f);
2011 }
2012 }
2013 Py_XDECREF(context);
2014 Py_XDECREF(cause);
2015 }
2016 }
2017 print_exception(f, value);
2018 if (err != 0)
2019 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002020}
2021
Thomas Wouters477c8d52006-05-27 19:21:47 +00002022void
2023PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 PyObject *seen;
Victor Stinner09054372013-11-06 22:41:44 +01002026 PyObject *f = _PySys_GetObjectId(&_PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +02002027 if (PyExceptionInstance_Check(value)
2028 && tb != NULL && PyTraceBack_Check(tb)) {
2029 /* Put the traceback on the exception, otherwise it won't get
2030 displayed. See issue #18776. */
2031 PyObject *cur_tb = PyException_GetTraceback(value);
2032 if (cur_tb == NULL)
2033 PyException_SetTraceback(value, tb);
2034 else
2035 Py_DECREF(cur_tb);
2036 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 if (f == Py_None) {
2038 /* pass */
2039 }
2040 else if (f == NULL) {
2041 _PyObject_Dump(value);
2042 fprintf(stderr, "lost sys.stderr\n");
2043 }
2044 else {
2045 /* We choose to ignore seen being possibly NULL, and report
2046 at least the main exception (it could be a MemoryError).
2047 */
2048 seen = PySet_New(NULL);
2049 if (seen == NULL)
2050 PyErr_Clear();
2051 print_exception_recursive(f, value, seen);
2052 Py_XDECREF(seen);
2053 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002054}
2055
Guido van Rossum82598051997-03-05 00:20:32 +00002056PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002057PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 PyObject *ret = NULL;
2061 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002062 PyArena *arena;
2063 _Py_static_string(PyId_string, "<string>");
2064 PyObject *filename;
2065
2066 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2067 if (filename == NULL)
2068 return NULL;
2069
2070 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 if (arena == NULL)
2072 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002073
Victor Stinner95701bd2013-11-06 18:41:07 +01002074 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002076 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 PyArena_Free(arena);
2078 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002079}
2080
2081PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002082PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002084{
Victor Stinner95701bd2013-11-06 18:41:07 +01002085 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002087 PyArena *arena = NULL;
2088 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002089
Victor Stinner95701bd2013-11-06 18:41:07 +01002090 filename = PyUnicode_DecodeFSDefault(filename_str);
2091 if (filename == NULL)
2092 goto exit;
2093
2094 arena = PyArena_New();
2095 if (arena == NULL)
2096 goto exit;
2097
2098 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2099 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002100 if (closeit)
2101 fclose(fp);
2102 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002103 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 }
2105 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002106
2107exit:
2108 Py_XDECREF(filename);
2109 if (arena != NULL)
2110 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002112}
2113
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002114static void
2115flush_io(void)
2116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 PyObject *f, *r;
2118 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002119 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 /* Save the current exception */
2122 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002123
Victor Stinner09054372013-11-06 22:41:44 +01002124 f = _PySys_GetObjectId(&_PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002126 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 if (r)
2128 Py_DECREF(r);
2129 else
2130 PyErr_Clear();
2131 }
Victor Stinner09054372013-11-06 22:41:44 +01002132 f = _PySys_GetObjectId(&_PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002134 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 if (r)
2136 Py_DECREF(r);
2137 else
2138 PyErr_Clear();
2139 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002142}
2143
Guido van Rossum82598051997-03-05 00:20:32 +00002144static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002145run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2146 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyCodeObject *co;
2149 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002150 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 if (co == NULL)
2152 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002153 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 Py_DECREF(co);
2155 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002156}
2157
Guido van Rossum82598051997-03-05 00:20:32 +00002158static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002159run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 PyCodeObject *co;
2163 PyObject *v;
2164 long magic;
2165 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 magic = PyMarshal_ReadLongFromFile(fp);
2168 if (magic != PyImport_GetMagicNumber()) {
2169 PyErr_SetString(PyExc_RuntimeError,
2170 "Bad magic number in .pyc file");
2171 return NULL;
2172 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002173 /* Skip mtime and size */
2174 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 (void) PyMarshal_ReadLongFromFile(fp);
2176 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002177 if (v == NULL || !PyCode_Check(v)) {
2178 Py_XDECREF(v);
2179 PyErr_SetString(PyExc_RuntimeError,
2180 "Bad code object in .pyc file");
2181 return NULL;
2182 }
2183 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002184 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 if (v && flags)
2186 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2187 Py_DECREF(co);
2188 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002189}
2190
Guido van Rossum82598051997-03-05 00:20:32 +00002191PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002192Py_CompileStringObject(const char *str, PyObject *filename, int start,
2193 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 PyCodeObject *co;
2196 mod_ty mod;
2197 PyArena *arena = PyArena_New();
2198 if (arena == NULL)
2199 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002200
Victor Stinner14e461d2013-08-26 22:28:21 +02002201 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 if (mod == NULL) {
2203 PyArena_Free(arena);
2204 return NULL;
2205 }
2206 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2207 PyObject *result = PyAST_mod2obj(mod);
2208 PyArena_Free(arena);
2209 return result;
2210 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002211 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 PyArena_Free(arena);
2213 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002214}
2215
Victor Stinner14e461d2013-08-26 22:28:21 +02002216PyObject *
2217Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2218 PyCompilerFlags *flags, int optimize)
2219{
2220 PyObject *filename, *co;
2221 filename = PyUnicode_DecodeFSDefault(filename_str);
2222 if (filename == NULL)
2223 return NULL;
2224 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2225 Py_DECREF(filename);
2226 return co;
2227}
2228
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002229/* For use in Py_LIMITED_API */
2230#undef Py_CompileString
2231PyObject *
2232PyCompileString(const char *str, const char *filename, int start)
2233{
2234 return Py_CompileStringFlags(str, filename, start, NULL);
2235}
2236
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002237struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002238Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 struct symtable *st;
2241 mod_ty mod;
2242 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002243 PyArena *arena;
2244
2245 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 if (arena == NULL)
2247 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002250 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 if (mod == NULL) {
2252 PyArena_Free(arena);
2253 return NULL;
2254 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002255 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 PyArena_Free(arena);
2257 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002258}
2259
Victor Stinner14e461d2013-08-26 22:28:21 +02002260struct symtable *
2261Py_SymtableString(const char *str, const char *filename_str, int start)
2262{
2263 PyObject *filename;
2264 struct symtable *st;
2265
2266 filename = PyUnicode_DecodeFSDefault(filename_str);
2267 if (filename == NULL)
2268 return NULL;
2269 st = Py_SymtableStringObject(str, filename, start);
2270 Py_DECREF(filename);
2271 return st;
2272}
2273
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274/* Preferred access to parser is through AST. */
2275mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002276PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2277 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 mod_ty mod;
2280 PyCompilerFlags localflags;
2281 perrdetail err;
2282 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002283
Victor Stinner14e461d2013-08-26 22:28:21 +02002284 node *n = PyParser_ParseStringObject(s, filename,
2285 &_PyParser_Grammar, start, &err,
2286 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (flags == NULL) {
2288 localflags.cf_flags = 0;
2289 flags = &localflags;
2290 }
2291 if (n) {
2292 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002293 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 }
2296 else {
2297 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002298 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002300 err_free(&err);
2301 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002302}
2303
2304mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002305PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2306 PyCompilerFlags *flags, PyArena *arena)
2307{
2308 PyObject *filename;
2309 mod_ty mod;
2310 filename = PyUnicode_DecodeFSDefault(filename_str);
2311 if (filename == NULL)
2312 return NULL;
2313 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2314 Py_DECREF(filename);
2315 return mod;
2316}
2317
2318mod_ty
2319PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2320 int start, char *ps1,
2321 char *ps2, PyCompilerFlags *flags, int *errcode,
2322 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 mod_ty mod;
2325 PyCompilerFlags localflags;
2326 perrdetail err;
2327 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002328
Victor Stinner14e461d2013-08-26 22:28:21 +02002329 node *n = PyParser_ParseFileObject(fp, filename, enc,
2330 &_PyParser_Grammar,
2331 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 if (flags == NULL) {
2333 localflags.cf_flags = 0;
2334 flags = &localflags;
2335 }
2336 if (n) {
2337 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002338 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 }
2341 else {
2342 err_input(&err);
2343 if (errcode)
2344 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002345 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002347 err_free(&err);
2348 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002349}
2350
Victor Stinner14e461d2013-08-26 22:28:21 +02002351mod_ty
2352PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2353 int start, char *ps1,
2354 char *ps2, PyCompilerFlags *flags, int *errcode,
2355 PyArena *arena)
2356{
2357 mod_ty mod;
2358 PyObject *filename;
2359 filename = PyUnicode_DecodeFSDefault(filename_str);
2360 if (filename == NULL)
2361 return NULL;
2362 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2363 flags, errcode, arena);
2364 Py_DECREF(filename);
2365 return mod;
2366}
2367
Guido van Rossuma110aa61994-08-29 12:50:44 +00002368/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002369
Guido van Rossuma110aa61994-08-29 12:50:44 +00002370node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002371PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 perrdetail err;
2374 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2375 &_PyParser_Grammar,
2376 start, NULL, NULL, &err, flags);
2377 if (n == NULL)
2378 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002379 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002382}
2383
Guido van Rossuma110aa61994-08-29 12:50:44 +00002384/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002385
Guido van Rossuma110aa61994-08-29 12:50:44 +00002386node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002387PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 perrdetail err;
2390 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2391 start, &err, flags);
2392 if (n == NULL)
2393 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002394 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002396}
2397
2398node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002399PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 perrdetail err;
2403 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2404 &_PyParser_Grammar, start, &err, flags);
2405 if (n == NULL)
2406 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002407 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002409}
2410
2411node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002412PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002415}
2416
Guido van Rossum66ebd912003-04-17 16:02:26 +00002417/* May want to move a more generalized form of this to parsetok.c or
2418 even parser modules. */
2419
2420void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002421PyParser_ClearError(perrdetail *err)
2422{
2423 err_free(err);
2424}
2425
2426void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002427PyParser_SetError(perrdetail *err)
2428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002430}
2431
Victor Stinner7f2fee32011-04-05 00:39:01 +02002432static void
2433err_free(perrdetail *err)
2434{
2435 Py_CLEAR(err->filename);
2436}
2437
Guido van Rossuma110aa61994-08-29 12:50:44 +00002438/* Set the error appropriate to the given input error code (see errcode.h) */
2439
2440static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002441err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 PyObject *v, *w, *errtype, *errtext;
2444 PyObject *msg_obj = NULL;
2445 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 errtype = PyExc_SyntaxError;
2448 switch (err->error) {
2449 case E_ERROR:
2450 return;
2451 case E_SYNTAX:
2452 errtype = PyExc_IndentationError;
2453 if (err->expected == INDENT)
2454 msg = "expected an indented block";
2455 else if (err->token == INDENT)
2456 msg = "unexpected indent";
2457 else if (err->token == DEDENT)
2458 msg = "unexpected unindent";
2459 else {
2460 errtype = PyExc_SyntaxError;
2461 msg = "invalid syntax";
2462 }
2463 break;
2464 case E_TOKEN:
2465 msg = "invalid token";
2466 break;
2467 case E_EOFS:
2468 msg = "EOF while scanning triple-quoted string literal";
2469 break;
2470 case E_EOLS:
2471 msg = "EOL while scanning string literal";
2472 break;
2473 case E_INTR:
2474 if (!PyErr_Occurred())
2475 PyErr_SetNone(PyExc_KeyboardInterrupt);
2476 goto cleanup;
2477 case E_NOMEM:
2478 PyErr_NoMemory();
2479 goto cleanup;
2480 case E_EOF:
2481 msg = "unexpected EOF while parsing";
2482 break;
2483 case E_TABSPACE:
2484 errtype = PyExc_TabError;
2485 msg = "inconsistent use of tabs and spaces in indentation";
2486 break;
2487 case E_OVERFLOW:
2488 msg = "expression too long";
2489 break;
2490 case E_DEDENT:
2491 errtype = PyExc_IndentationError;
2492 msg = "unindent does not match any outer indentation level";
2493 break;
2494 case E_TOODEEP:
2495 errtype = PyExc_IndentationError;
2496 msg = "too many levels of indentation";
2497 break;
2498 case E_DECODE: {
2499 PyObject *type, *value, *tb;
2500 PyErr_Fetch(&type, &value, &tb);
2501 msg = "unknown decode error";
2502 if (value != NULL)
2503 msg_obj = PyObject_Str(value);
2504 Py_XDECREF(type);
2505 Py_XDECREF(value);
2506 Py_XDECREF(tb);
2507 break;
2508 }
2509 case E_LINECONT:
2510 msg = "unexpected character after line continuation character";
2511 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 case E_IDENTIFIER:
2514 msg = "invalid character in identifier";
2515 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002516 case E_BADSINGLE:
2517 msg = "multiple statements found while compiling a single statement";
2518 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 default:
2520 fprintf(stderr, "error=%d\n", err->error);
2521 msg = "unknown parsing error";
2522 break;
2523 }
2524 /* err->text may not be UTF-8 in case of decoding errors.
2525 Explicitly convert to an object. */
2526 if (!err->text) {
2527 errtext = Py_None;
2528 Py_INCREF(Py_None);
2529 } else {
2530 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2531 "replace");
2532 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002533 v = Py_BuildValue("(OiiN)", err->filename,
2534 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 if (v != NULL) {
2536 if (msg_obj)
2537 w = Py_BuildValue("(OO)", msg_obj, v);
2538 else
2539 w = Py_BuildValue("(sO)", msg, v);
2540 } else
2541 w = NULL;
2542 Py_XDECREF(v);
2543 PyErr_SetObject(errtype, w);
2544 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002545cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 Py_XDECREF(msg_obj);
2547 if (err->text != NULL) {
2548 PyObject_FREE(err->text);
2549 err->text = NULL;
2550 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002551}
2552
2553/* Print fatal error message and abort */
2554
2555void
Tim Peters7c321a82002-07-09 02:57:01 +00002556Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002557{
Victor Stinner024e37a2011-03-31 01:31:06 +02002558 const int fd = fileno(stderr);
2559 PyThreadState *tstate;
2560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 fprintf(stderr, "Fatal Python error: %s\n", msg);
2562 fflush(stderr); /* it helps in Windows debug build */
2563 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002564 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002566 else {
2567 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2568 if (tstate != NULL) {
2569 fputc('\n', stderr);
2570 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002571 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002572 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002573 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002574 }
2575
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002576#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 {
2578 size_t len = strlen(msg);
2579 WCHAR* buffer;
2580 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 /* Convert the message to wchar_t. This uses a simple one-to-one
2583 conversion, assuming that the this error message actually uses ASCII
2584 only. If this ceases to be true, we will have to convert. */
2585 buffer = alloca( (len+1) * (sizeof *buffer));
2586 for( i=0; i<=len; ++i)
2587 buffer[i] = msg[i];
2588 OutputDebugStringW(L"Fatal Python error: ");
2589 OutputDebugStringW(buffer);
2590 OutputDebugStringW(L"\n");
2591 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002592#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002594#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002595#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002597}
2598
2599/* Clean up and exit */
2600
Guido van Rossuma110aa61994-08-29 12:50:44 +00002601#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002602#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002603#endif
2604
Collin Winter670e6922007-03-21 02:57:17 +00002605static void (*pyexitfunc)(void) = NULL;
2606/* For the atexit module. */
2607void _Py_PyAtExit(void (*func)(void))
2608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002609 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002610}
2611
2612static void
2613call_py_exitfuncs(void)
2614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 if (pyexitfunc == NULL)
2616 return;
Collin Winter670e6922007-03-21 02:57:17 +00002617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 (*pyexitfunc)();
2619 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002620}
2621
Antoine Pitrou011bd622009-10-20 21:52:47 +00002622/* Wait until threading._shutdown completes, provided
2623 the threading module was imported in the first place.
2624 The shutdown routine will wait until all non-daemon
2625 "threading" threads have completed. */
2626static void
2627wait_for_thread_shutdown(void)
2628{
2629#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002630 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 PyObject *result;
2632 PyThreadState *tstate = PyThreadState_GET();
2633 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2634 "threading");
2635 if (threading == NULL) {
2636 /* threading not imported */
2637 PyErr_Clear();
2638 return;
2639 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002640 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 if (result == NULL) {
2642 PyErr_WriteUnraisable(threading);
2643 }
2644 else {
2645 Py_DECREF(result);
2646 }
2647 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002648#endif
2649}
2650
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002651#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002652static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002653static int nexitfuncs = 0;
2654
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002655int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 if (nexitfuncs >= NEXITFUNCS)
2658 return -1;
2659 exitfuncs[nexitfuncs++] = func;
2660 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002661}
2662
Guido van Rossumcc283f51997-08-05 02:22:03 +00002663static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002664call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002666 while (nexitfuncs > 0)
2667 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 fflush(stdout);
2670 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002671}
2672
2673void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002674Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002676 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002679}
2680
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002681static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002682initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002683{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002684#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002686#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002687#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002688 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002689#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002690#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002692#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002694 if (PyErr_Occurred()) {
2695 Py_FatalError("Py_Initialize: can't import signal");
2696 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002697}
2698
Guido van Rossum7433b121997-02-14 19:45:36 +00002699
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002700/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2701 *
2702 * All of the code in this function must only use async-signal-safe functions,
2703 * listed at `man 7 signal` or
2704 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2705 */
2706void
2707_Py_RestoreSignals(void)
2708{
2709#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002711#endif
2712#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002714#endif
2715#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002717#endif
2718}
2719
2720
Guido van Rossum7433b121997-02-14 19:45:36 +00002721/*
2722 * The file descriptor fd is considered ``interactive'' if either
2723 * a) isatty(fd) is TRUE, or
2724 * b) the -i flag was given, and the filename associated with
2725 * the descriptor is NULL or "<stdin>" or "???".
2726 */
2727int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002728Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 if (isatty((int)fileno(fp)))
2731 return 1;
2732 if (!Py_InteractiveFlag)
2733 return 0;
2734 return (filename == NULL) ||
2735 (strcmp(filename, "<stdin>") == 0) ||
2736 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002737}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002738
2739
Tim Petersd08e3822003-04-17 15:24:21 +00002740#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002741#if defined(WIN32) && defined(_MSC_VER)
2742
2743/* Stack checking for Microsoft C */
2744
2745#include <malloc.h>
2746#include <excpt.h>
2747
Fred Drakee8de31c2000-08-31 05:38:39 +00002748/*
2749 * Return non-zero when we run out of memory on the stack; zero otherwise.
2750 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002751int
Fred Drake399739f2000-08-31 05:52:44 +00002752PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 __try {
2755 /* alloca throws a stack overflow exception if there's
2756 not enough space left on the stack */
2757 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2758 return 0;
2759 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2760 EXCEPTION_EXECUTE_HANDLER :
2761 EXCEPTION_CONTINUE_SEARCH) {
2762 int errcode = _resetstkoflw();
2763 if (errcode == 0)
2764 {
2765 Py_FatalError("Could not reset the stack!");
2766 }
2767 }
2768 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002769}
2770
2771#endif /* WIN32 && _MSC_VER */
2772
2773/* Alternate implementations can be added here... */
2774
2775#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002776
2777
2778/* Wrappers around sigaction() or signal(). */
2779
2780PyOS_sighandler_t
2781PyOS_getsig(int sig)
2782{
2783#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 struct sigaction context;
2785 if (sigaction(sig, NULL, &context) == -1)
2786 return SIG_ERR;
2787 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002788#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002790/* Special signal handling for the secure CRT in Visual Studio 2005 */
2791#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 switch (sig) {
2793 /* Only these signals are valid */
2794 case SIGINT:
2795 case SIGILL:
2796 case SIGFPE:
2797 case SIGSEGV:
2798 case SIGTERM:
2799 case SIGBREAK:
2800 case SIGABRT:
2801 break;
2802 /* Don't call signal() with other values or it will assert */
2803 default:
2804 return SIG_ERR;
2805 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002806#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 handler = signal(sig, SIG_IGN);
2808 if (handler != SIG_ERR)
2809 signal(sig, handler);
2810 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002811#endif
2812}
2813
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002814/*
2815 * All of the code in this function must only use async-signal-safe functions,
2816 * listed at `man 7 signal` or
2817 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2818 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002819PyOS_sighandler_t
2820PyOS_setsig(int sig, PyOS_sighandler_t handler)
2821{
2822#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 /* Some code in Modules/signalmodule.c depends on sigaction() being
2824 * used here if HAVE_SIGACTION is defined. Fix that if this code
2825 * changes to invalidate that assumption.
2826 */
2827 struct sigaction context, ocontext;
2828 context.sa_handler = handler;
2829 sigemptyset(&context.sa_mask);
2830 context.sa_flags = 0;
2831 if (sigaction(sig, &context, &ocontext) == -1)
2832 return SIG_ERR;
2833 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002834#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 PyOS_sighandler_t oldhandler;
2836 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002837#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002839#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002841#endif
2842}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002843
2844/* Deprecated C API functions still provided for binary compatiblity */
2845
2846#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002847PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002848PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002851}
2852
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002853#undef PyParser_SimpleParseString
2854PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855PyParser_SimpleParseString(const char *str, int start)
2856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002858}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002859
2860#undef PyRun_AnyFile
2861PyAPI_FUNC(int)
2862PyRun_AnyFile(FILE *fp, const char *name)
2863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002865}
2866
2867#undef PyRun_AnyFileEx
2868PyAPI_FUNC(int)
2869PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002872}
2873
2874#undef PyRun_AnyFileFlags
2875PyAPI_FUNC(int)
2876PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002879}
2880
2881#undef PyRun_File
2882PyAPI_FUNC(PyObject *)
2883PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2884{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002886}
2887
2888#undef PyRun_FileEx
2889PyAPI_FUNC(PyObject *)
2890PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002893}
2894
2895#undef PyRun_FileFlags
2896PyAPI_FUNC(PyObject *)
2897PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002898 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002901}
2902
2903#undef PyRun_SimpleFile
2904PyAPI_FUNC(int)
2905PyRun_SimpleFile(FILE *f, const char *p)
2906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002908}
2909
2910#undef PyRun_SimpleFileEx
2911PyAPI_FUNC(int)
2912PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002914 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002915}
2916
2917
2918#undef PyRun_String
2919PyAPI_FUNC(PyObject *)
2920PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002922 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002923}
2924
2925#undef PyRun_SimpleString
2926PyAPI_FUNC(int)
2927PyRun_SimpleString(const char *s)
2928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002930}
2931
2932#undef Py_CompileString
2933PyAPI_FUNC(PyObject *)
2934Py_CompileString(const char *str, const char *p, int s)
2935{
Georg Brandl8334fd92010-12-04 10:26:46 +00002936 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2937}
2938
2939#undef Py_CompileStringFlags
2940PyAPI_FUNC(PyObject *)
2941Py_CompileStringFlags(const char *str, const char *p, int s,
2942 PyCompilerFlags *flags)
2943{
2944 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002945}
2946
2947#undef PyRun_InteractiveOne
2948PyAPI_FUNC(int)
2949PyRun_InteractiveOne(FILE *f, const char *p)
2950{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002952}
2953
2954#undef PyRun_InteractiveLoop
2955PyAPI_FUNC(int)
2956PyRun_InteractiveLoop(FILE *f, const char *p)
2957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002959}
2960
2961#ifdef __cplusplus
2962}
2963#endif