blob: 61d03521e8ed3885465a2e38d9742d6893e52a63 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Ezio Melotti1f8898a2013-03-26 01:59:56 +020038#ifdef Py_REF_DEBUG
Antoine Pitrou208ac5c2013-04-24 20:17:53 +020039static
40void _print_total_refs(void) {
Victor Stinner4ee41c52013-11-06 18:28:21 +010041 PyObject *xoptions, *value;
42 _Py_IDENTIFIER(showrefcount);
43
Ezio Melotti1f8898a2013-03-26 01:59:56 +020044 xoptions = PySys_GetXOptions();
45 if (xoptions == NULL)
46 return;
Victor Stinner4ee41c52013-11-06 18:28:21 +010047 value = _PyDict_GetItemId(xoptions, &PyId_showrefcount);
Ezio Melotti1f8898a2013-03-26 01:59:56 +020048 if (value == Py_True)
49 fprintf(stderr,
50 "[%" PY_FORMAT_SIZE_T "d refs, "
51 "%" PY_FORMAT_SIZE_T "d blocks]\n",
52 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
53}
54#endif
55
Neal Norwitz4281cef2006-03-04 19:58:13 +000056#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000058#else /* Py_REF_DEBUG */
Ezio Melotti1f8898a2013-03-26 01:59:56 +020059#define PRINT_TOTAL_REFS() _print_total_refs()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000060#endif
61
62#ifdef __cplusplus
63extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000064#endif
65
Martin v. Löwis790465f2008-04-05 20:41:37 +000066extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000067
Guido van Rossum82598051997-03-05 00:20:32 +000068extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000069
Guido van Rossumb73cc041993-11-01 16:28:59 +000070/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100071static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020072static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000073static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000074static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000075static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010076static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000078static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000080static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020081static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000082static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000083static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000084static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000085static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +020086extern int _PyUnicode_Init(void);
Victor Stinner26f91992013-07-17 01:22:45 +020087extern int _PyStructSequence_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000088extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000089extern int _PyLong_Init(void);
90extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020091extern int _PyFaulthandler_Init(void);
92extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000093
Mark Hammond8d98d2c2003-04-19 15:41:53 +000094#ifdef WITH_THREAD
95extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
96extern void _PyGILState_Fini(void);
97#endif /* WITH_THREAD */
98
Guido van Rossum82598051997-03-05 00:20:32 +000099int Py_DebugFlag; /* Needed by parser.c */
100int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000101int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000102int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200103int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000104int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000105int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000106int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000107int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000108int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000109int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000110int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000111int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100112int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200113int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000114
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200115PyThreadState *_Py_Finalizing = NULL;
116
Christian Heimes49e61802013-10-22 10:22:29 +0200117/* Hack to force loading of object files */
118int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
119 PyOS_mystrnicmp; /* Python/pystrcmp.o */
120
Christian Heimes33fe8092008-04-13 13:53:33 +0000121/* PyModule_GetWarningsModule is no longer necessary as of 2.6
122since _warnings is builtin. This API should not be used. */
123PyObject *
124PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000127}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000128
Guido van Rossum25ce5661997-08-02 03:10:38 +0000129static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000130
Thomas Wouters7e474022000-07-16 12:04:32 +0000131/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000132
133int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000134Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000137}
138
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000139/* Helper to allow an embedding application to override the normal
140 * mechanism that attempts to figure out an appropriate IO encoding
141 */
142
143static char *_Py_StandardStreamEncoding = NULL;
144static char *_Py_StandardStreamErrors = NULL;
145
146int
147Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
148{
149 if (Py_IsInitialized()) {
150 /* This is too late to have any effect */
151 return -1;
152 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000153 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
154 * initialised yet.
155 *
156 * However, the raw memory allocators are initialised appropriately
157 * as C static variables, so _PyMem_RawStrdup is OK even though
158 * Py_Initialize hasn't been called yet.
159 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000160 if (encoding) {
161 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
162 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000163 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000164 }
165 }
166 if (errors) {
167 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
168 if (!_Py_StandardStreamErrors) {
169 if (_Py_StandardStreamEncoding) {
170 PyMem_RawFree(_Py_StandardStreamEncoding);
171 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000172 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000173 }
174 }
175 return 0;
176}
177
Guido van Rossum25ce5661997-08-02 03:10:38 +0000178/* Global initializations. Can be undone by Py_Finalize(). Don't
179 call this twice without an intervening Py_Finalize() call. When
180 initializations fail, a fatal error is issued and the function does
181 not return. On return, the first thread and interpreter state have
182 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000183
Guido van Rossum25ce5661997-08-02 03:10:38 +0000184 Locking: you must hold the interpreter lock while calling this.
185 (If the lock has not yet been initialized, that's equivalent to
186 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000187
Guido van Rossum25ce5661997-08-02 03:10:38 +0000188*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000189
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000190static int
191add_flag(int flag, const char *envs)
192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 int env = atoi(envs);
194 if (flag < env)
195 flag = env;
196 if (flag < 1)
197 flag = 1;
198 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000199}
200
Christian Heimes5833a2f2008-10-30 21:40:04 +0000201static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000202get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000203{
Victor Stinner94908bb2010-08-18 21:23:25 +0000204 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000205 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200206 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000207
Victor Stinner94908bb2010-08-18 21:23:25 +0000208 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 if (!codec)
210 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000211
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200212 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 Py_CLEAR(codec);
214 if (!name)
215 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000216
Victor Stinner94908bb2010-08-18 21:23:25 +0000217 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100218 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000219 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200220 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000222 if (name_str == NULL) {
223 PyErr_NoMemory();
224 return NULL;
225 }
226 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000227
228error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000230 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000232}
Victor Stinner94908bb2010-08-18 21:23:25 +0000233
Victor Stinner94908bb2010-08-18 21:23:25 +0000234static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200235get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000236{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200237#ifdef MS_WINDOWS
238 char codepage[100];
239 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
240 return get_codec_name(codepage);
241#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000242 char* codeset = nl_langinfo(CODESET);
243 if (!codeset || codeset[0] == '\0') {
244 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
245 return NULL;
246 }
247 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200248#else
249 PyErr_SetNone(PyExc_NotImplementedError);
250 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000251#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200252}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000253
Brett Cannonfd074152012-04-14 14:10:13 -0400254static void
255import_init(PyInterpreterState *interp, PyObject *sysmod)
256{
257 PyObject *importlib;
258 PyObject *impmod;
259 PyObject *sys_modules;
260 PyObject *value;
261
262 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400263 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
264 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
265 }
266 else if (Py_VerboseFlag) {
267 PySys_FormatStderr("import _frozen_importlib # frozen\n");
268 }
269 importlib = PyImport_AddModule("_frozen_importlib");
270 if (importlib == NULL) {
271 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
272 "sys.modules");
273 }
274 interp->importlib = importlib;
275 Py_INCREF(interp->importlib);
276
277 /* Install _importlib as __import__ */
278 impmod = PyInit_imp();
279 if (impmod == NULL) {
280 Py_FatalError("Py_Initialize: can't import imp");
281 }
282 else if (Py_VerboseFlag) {
283 PySys_FormatStderr("import imp # builtin\n");
284 }
285 sys_modules = PyImport_GetModuleDict();
286 if (Py_VerboseFlag) {
287 PySys_FormatStderr("import sys # builtin\n");
288 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400289 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
290 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400291 }
292
Brett Cannone0d88a12012-04-25 20:54:04 -0400293 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400294 if (value == NULL) {
295 PyErr_Print();
296 Py_FatalError("Py_Initialize: importlib install failed");
297 }
298 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400299 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400300
301 _PyImportZip_Init();
302}
303
304
Guido van Rossuma027efa1997-05-05 20:56:21 +0000305void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200306_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 PyInterpreterState *interp;
309 PyThreadState *tstate;
310 PyObject *bimod, *sysmod, *pstderr;
311 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (initialized)
315 return;
316 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200317 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000318
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000319#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 /* Set up the LC_CTYPE locale, so we can obtain
321 the locale's charset without having to switch
322 locales. */
323 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000324#endif
325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
327 Py_DebugFlag = add_flag(Py_DebugFlag, p);
328 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
329 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
330 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
331 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
332 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
333 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100334 /* The variable is only tested for existence here; _PyRandom_Init will
335 check its value further. */
336 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
337 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
338
339 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 interp = PyInterpreterState_New();
342 if (interp == NULL)
343 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 tstate = PyThreadState_New(interp);
346 if (tstate == NULL)
347 Py_FatalError("Py_Initialize: can't make first thread");
348 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000349
Victor Stinner6961bd62010-08-17 22:26:51 +0000350#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000351 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
352 destroying the GIL might fail when it is being referenced from
353 another running thread (see issue #9901).
354 Instead we destroy the previously created GIL here, which ensures
355 that we can call Py_Initialize / Py_Finalize multiple times. */
356 _PyEval_FiniThreads();
357
358 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000359 _PyGILState_Init(interp, tstate);
360#endif /* WITH_THREAD */
361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (!_PyFrame_Init())
365 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (!_PyLong_Init())
368 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 if (!PyByteArray_Init())
371 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000372
Victor Stinner1c8f0592013-07-22 22:24:54 +0200373 if (!_PyFloat_Init())
374 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 interp->modules = PyDict_New();
377 if (interp->modules == NULL)
378 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200381 if (_PyUnicode_Init() < 0)
382 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200383 if (_PyStructSequence_Init() < 0)
384 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 bimod = _PyBuiltin_Init();
387 if (bimod == NULL)
388 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000389 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 interp->builtins = PyModule_GetDict(bimod);
391 if (interp->builtins == NULL)
392 Py_FatalError("Py_Initialize: can't initialize builtins dict");
393 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400396 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 sysmod = _PySys_Init();
399 if (sysmod == NULL)
400 Py_FatalError("Py_Initialize: can't initialize sys");
401 interp->sysdict = PyModule_GetDict(sysmod);
402 if (interp->sysdict == NULL)
403 Py_FatalError("Py_Initialize: can't initialize sys dict");
404 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000405 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 PySys_SetPath(Py_GetPath());
407 PyDict_SetItemString(interp->sysdict, "modules",
408 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 /* Set up a preliminary stderr printer until we have enough
411 infrastructure for the io module in place. */
412 pstderr = PyFile_NewStdPrinter(fileno(stderr));
413 if (pstderr == NULL)
414 Py_FatalError("Py_Initialize: can't set preliminary stderr");
415 PySys_SetObject("stderr", pstderr);
416 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000417 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000422
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000423 /* Initialize _warnings. */
424 _PyWarnings_Init();
425
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200426 if (!install_importlib)
427 return;
428
Brett Cannonfd074152012-04-14 14:10:13 -0400429 import_init(interp, sysmod);
430
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200431 /* initialize the faulthandler module */
432 if (_PyFaulthandler_Init())
433 Py_FatalError("Py_Initialize: can't initialize faulthandler");
434
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000435 _PyTime_Init();
436
Victor Stinner793b5312011-04-27 00:24:21 +0200437 if (initfsencoding(interp) < 0)
438 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 if (install_sigs)
441 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000442
Nick Coghlan85e729e2012-07-15 18:09:52 +1000443 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 if (initstdio() < 0)
445 Py_FatalError(
446 "Py_Initialize: can't initialize sys standard streams");
447
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000448 /* Initialize warnings. */
449 if (PySys_HasWarnOptions()) {
450 PyObject *warnings_module = PyImport_ImportModule("warnings");
451 if (warnings_module == NULL) {
452 fprintf(stderr, "'import warnings' failed; traceback:\n");
453 PyErr_Print();
454 }
455 Py_XDECREF(warnings_module);
456 }
457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (!Py_NoSiteFlag)
459 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000460}
461
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000462void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200463Py_InitializeEx(int install_sigs)
464{
465 _Py_InitializeEx_Private(install_sigs, 1);
466}
467
468void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000469Py_Initialize(void)
470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000472}
473
474
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000475#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000476extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000477#endif
478
Guido van Rossume8432ac2007-07-09 15:04:50 +0000479/* Flush stdout and stderr */
480
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100481static int
482file_is_closed(PyObject *fobj)
483{
484 int r;
485 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
486 if (tmp == NULL) {
487 PyErr_Clear();
488 return 0;
489 }
490 r = PyObject_IsTrue(tmp);
491 Py_DECREF(tmp);
492 if (r < 0)
493 PyErr_Clear();
494 return r > 0;
495}
496
Neal Norwitz2bad9702007-08-27 06:19:22 +0000497static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000498flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 PyObject *fout = PySys_GetObject("stdout");
501 PyObject *ferr = PySys_GetObject("stderr");
502 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200503 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000504
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100505 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200506 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000508 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 else
510 Py_DECREF(tmp);
511 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000512
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100513 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200514 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (tmp == NULL)
516 PyErr_Clear();
517 else
518 Py_DECREF(tmp);
519 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000520}
521
Guido van Rossum25ce5661997-08-02 03:10:38 +0000522/* Undo the effect of Py_Initialize().
523
524 Beware: if multiple interpreter and/or thread states exist, these
525 are not wiped out; only the current thread and interpreter state
526 are deleted. But since everything else is deleted, those other
527 interpreter and thread states should no longer be used.
528
529 (XXX We should do better, e.g. wipe out all interpreters and
530 threads.)
531
532 Locking: as above.
533
534*/
535
536void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000537Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 PyInterpreterState *interp;
540 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (!initialized)
543 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 /* The interpreter is still entirely intact at this point, and the
548 * exit funcs may be relying on that. In particular, if some thread
549 * or exit func is still waiting to do an import, the import machinery
550 * expects Py_IsInitialized() to return true. So don't say the
551 * interpreter is uninitialized until after the exit funcs have run.
552 * Note that Threading.py uses an exit func to do a join on all the
553 * threads created thru it, so this also protects pending imports in
554 * the threads created via Threading.
555 */
556 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 /* Get current thread state and interpreter pointer */
559 tstate = PyThreadState_GET();
560 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200562 /* Remaining threads (e.g. daemon threads) will automatically exit
563 after taking the GIL (in PyEval_RestoreThread()). */
564 _Py_Finalizing = tstate;
565 initialized = 0;
566
567 /* Flush stdout+stderr */
568 flush_std_files();
569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 /* Disable signal handling */
571 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 /* Collect garbage. This may call finalizers; it's nice to call these
574 * before all modules are destroyed.
575 * XXX If a __del__ or weakref callback is triggered here, and tries to
576 * XXX import a module, bad things can happen, because Python no
577 * XXX longer believes it's initialized.
578 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
579 * XXX is easy to provoke that way. I've also seen, e.g.,
580 * XXX Exception exceptions.ImportError: 'No module named sha'
581 * XXX in <function callback at 0x008F5718> ignored
582 * XXX but I'm unclear on exactly how that one happens. In any case,
583 * XXX I haven't seen a real-life report of either of these.
584 */
585 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000586#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 /* With COUNT_ALLOCS, it helps to run GC multiple times:
588 each collection might release some types from the type
589 list, so they become garbage. */
590 while (PyGC_Collect() > 0)
591 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000592#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 /* Destroy all modules */
594 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 /* Flush stdout+stderr (again, in case more was printed) */
597 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100600 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 * XXX This is disabled because it caused too many problems. If
602 * XXX a __del__ or weakref callback triggers here, Python code has
603 * XXX a hard time running, because even the sys module has been
604 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
605 * XXX One symptom is a sequence of information-free messages
606 * XXX coming from threads (if a __del__ or callback is invoked,
607 * XXX other threads can execute too, and any exception they encounter
608 * XXX triggers a comedy of errors as subsystem after subsystem
609 * XXX fails to find what it *expects* to find in sys to help report
610 * XXX the exception and consequent unexpected failures). I've also
611 * XXX seen segfaults then, after adding print statements to the
612 * XXX Python code getting called.
613 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000614#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000616#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
619 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000620
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200621 /* Cleanup typeobject.c's internal caches. */
622 _PyType_Fini();
623
Victor Stinner024e37a2011-03-31 01:31:06 +0200624 /* unload faulthandler module */
625 _PyFaulthandler_Fini();
626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000628#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000630#endif
631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000633
Tim Peters9cf25ce2003-04-17 15:21:01 +0000634#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 /* Display all objects still alive -- this can invoke arbitrary
636 * __repr__ overrides, so requires a mostly-intact interpreter.
637 * Alas, a lot of stuff may still be alive now that will be cleaned
638 * up later.
639 */
640 if (Py_GETENV("PYTHONDUMPREFS"))
641 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000642#endif /* Py_TRACE_REFS */
643
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200644 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 /* Now we decref the exception classes. After this point nothing
648 can raise an exception. That's okay, because each Fini() method
649 below has been checked to make sure no exceptions are ever
650 raised.
651 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 /* Sundry finalizers */
656 PyMethod_Fini();
657 PyFrame_Fini();
658 PyCFunction_Fini();
659 PyTuple_Fini();
660 PyList_Fini();
661 PySet_Fini();
662 PyBytes_Fini();
663 PyByteArray_Fini();
664 PyLong_Fini();
665 PyFloat_Fini();
666 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100667 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200668 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200669 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000670
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 /* Cleanup Unicode implementation */
672 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000675 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200676 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 Py_FileSystemDefaultEncoding = NULL;
678 }
Christian Heimesc8967002007-11-30 10:18:26 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 /* XXX Still allocated:
681 - various static ad-hoc pointers to interned strings
682 - int and float free list blocks
683 - whatever various modules and libraries allocate
684 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000687
Victor Stinner51fa4582013-07-07 15:50:49 +0200688 /* Cleanup auto-thread-state */
689#ifdef WITH_THREAD
690 _PyGILState_Fini();
691#endif /* WITH_THREAD */
692
693 /* Delete current thread. After this, many C API calls become crashy. */
694 PyThreadState_Swap(NULL);
695 PyInterpreterState_Delete(interp);
696
Tim Peters269b2a62003-04-17 19:52:29 +0000697#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 /* Display addresses (& refcnts) of all objects still alive.
699 * An address can be used to find the repr of the object, printed
700 * above by _Py_PrintReferences.
701 */
702 if (Py_GETENV("PYTHONDUMPREFS"))
703 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000704#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000705#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400707 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000708#endif
709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000711}
712
713/* Create and initialize a new interpreter and thread, and return the
714 new thread. This requires that Py_Initialize() has been called
715 first.
716
717 Unsuccessful initialization yields a NULL pointer. Note that *no*
718 exception information is available even in this case -- the
719 exception information is held in the thread, and there is no
720 thread.
721
722 Locking: as above.
723
724*/
725
726PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000727Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyInterpreterState *interp;
730 PyThreadState *tstate, *save_tstate;
731 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (!initialized)
734 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 interp = PyInterpreterState_New();
737 if (interp == NULL)
738 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 tstate = PyThreadState_New(interp);
741 if (tstate == NULL) {
742 PyInterpreterState_Delete(interp);
743 return NULL;
744 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000751
Victor Stinner49d3f252010-10-17 01:24:53 +0000752 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (bimod != NULL) {
754 interp->builtins = PyModule_GetDict(bimod);
755 if (interp->builtins == NULL)
756 goto handle_error;
757 Py_INCREF(interp->builtins);
758 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400761 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000762
Victor Stinner49d3f252010-10-17 01:24:53 +0000763 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (bimod != NULL && sysmod != NULL) {
765 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 interp->sysdict = PyModule_GetDict(sysmod);
768 if (interp->sysdict == NULL)
769 goto handle_error;
770 Py_INCREF(interp->sysdict);
771 PySys_SetPath(Py_GetPath());
772 PyDict_SetItemString(interp->sysdict, "modules",
773 interp->modules);
774 /* Set up a preliminary stderr printer until we have enough
775 infrastructure for the io module in place. */
776 pstderr = PyFile_NewStdPrinter(fileno(stderr));
777 if (pstderr == NULL)
778 Py_FatalError("Py_Initialize: can't set preliminary stderr");
779 PySys_SetObject("stderr", pstderr);
780 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000781 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200784
Brett Cannonfd074152012-04-14 14:10:13 -0400785 import_init(interp, sysmod);
786
Victor Stinner793b5312011-04-27 00:24:21 +0200787 if (initfsencoding(interp) < 0)
788 goto handle_error;
789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (initstdio() < 0)
791 Py_FatalError(
792 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000793 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 if (!Py_NoSiteFlag)
795 initsite();
796 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 if (!PyErr_Occurred())
799 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000800
Thomas Wouters89f507f2006-12-13 04:49:30 +0000801handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000803
Victor Stinnerc40a3502011-04-27 00:20:27 +0200804 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 PyThreadState_Clear(tstate);
806 PyThreadState_Swap(save_tstate);
807 PyThreadState_Delete(tstate);
808 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000811}
812
813/* Delete an interpreter and its last thread. This requires that the
814 given thread state is current, that the thread has no remaining
815 frames, and that it is its interpreter's only remaining thread.
816 It is a fatal error to violate these constraints.
817
818 (Py_Finalize() doesn't have these constraints -- it zaps
819 everything, regardless.)
820
821 Locking: as above.
822
823*/
824
825void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000826Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (tstate != PyThreadState_GET())
831 Py_FatalError("Py_EndInterpreter: thread is not current");
832 if (tstate->frame != NULL)
833 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200834
835 wait_for_thread_shutdown();
836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 if (tstate != interp->tstate_head || tstate->next != NULL)
838 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyImport_Cleanup();
841 PyInterpreterState_Clear(interp);
842 PyThreadState_Swap(NULL);
843 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000844}
845
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200846#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000847static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200848#else
849static wchar_t *progname = L"python3";
850#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000851
852void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000853Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000854{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (pn && *pn)
856 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000857}
858
Martin v. Löwis790465f2008-04-05 20:41:37 +0000859wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000860Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000863}
864
Martin v. Löwis790465f2008-04-05 20:41:37 +0000865static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200866static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000867
868void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000869Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000872}
873
Martin v. Löwis790465f2008-04-05 20:41:37 +0000874wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000875Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 wchar_t *home = default_home;
878 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
879 char* chome = Py_GETENV("PYTHONHOME");
880 if (chome) {
881 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
882 if (r != (size_t)-1 && r <= PATH_MAX)
883 home = env_home;
884 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 }
887 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000888}
889
Guido van Rossum6135a871995-01-09 17:53:26 +0000890/* Create __main__ module */
891
892static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000893initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000894{
Brett Cannon13853a62013-05-04 17:37:09 -0400895 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 m = PyImport_AddModule("__main__");
897 if (m == NULL)
898 Py_FatalError("can't create __main__ module");
899 d = PyModule_GetDict(m);
900 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
901 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000902 if (bimod == NULL) {
903 Py_FatalError("Failed to retrieve builtins module");
904 }
905 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
906 Py_FatalError("Failed to initialize __main__.__builtins__");
907 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 Py_DECREF(bimod);
909 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000910 /* Main is a little special - imp.is_builtin("__main__") will return
911 * False, but BuiltinImporter is still the most appropriate initial
912 * setting for its __loader__ attribute. A more suitable value will
913 * be set if __main__ gets further initialized later in the startup
914 * process.
915 */
Brett Cannon13853a62013-05-04 17:37:09 -0400916 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400917 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000918 PyObject *loader = PyObject_GetAttrString(interp->importlib,
919 "BuiltinImporter");
920 if (loader == NULL) {
921 Py_FatalError("Failed to retrieve BuiltinImporter");
922 }
923 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
924 Py_FatalError("Failed to initialize __main__.__loader__");
925 }
926 Py_DECREF(loader);
927 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000928}
929
Victor Stinner793b5312011-04-27 00:24:21 +0200930static int
931initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000932{
933 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000934
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200935 if (Py_FileSystemDefaultEncoding == NULL)
936 {
937 Py_FileSystemDefaultEncoding = get_locale_encoding();
938 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000939 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000940
Victor Stinnere4743092010-10-19 00:05:51 +0000941 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200942 interp->fscodec_initialized = 1;
943 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000944 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000945
946 /* the encoding is mbcs, utf-8 or ascii */
947 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
948 if (!codec) {
949 /* Such error can only occurs in critical situations: no more
950 * memory, import a module of the standard library failed,
951 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200952 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000953 }
Victor Stinner793b5312011-04-27 00:24:21 +0200954 Py_DECREF(codec);
955 interp->fscodec_initialized = 1;
956 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000957}
958
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000959/* Import the site module (not into __main__ though) */
960
961static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000962initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 PyObject *m;
965 m = PyImport_ImportModule("site");
966 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200967 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PyErr_Print();
969 Py_Finalize();
970 exit(1);
971 }
972 else {
973 Py_DECREF(m);
974 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000975}
976
Antoine Pitrou05608432009-01-09 18:53:14 +0000977static PyObject*
978create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 int fd, int write_mode, char* name,
980 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000981{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
983 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000984 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 PyObject *line_buffering;
986 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200987 _Py_IDENTIFIER(open);
988 _Py_IDENTIFIER(isatty);
989 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200990 _Py_IDENTIFIER(name);
991 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 /* stdin is always opened in buffered mode, first because it shouldn't
994 make a difference in common use cases, second because TextIOWrapper
995 depends on the presence of a read1() method which only exists on
996 buffered streams.
997 */
998 if (Py_UnbufferedStdioFlag && write_mode)
999 buffering = 0;
1000 else
1001 buffering = -1;
1002 if (write_mode)
1003 mode = "wb";
1004 else
1005 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001006 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1007 fd, mode, buffering,
1008 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (buf == NULL)
1010 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001011
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001013 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001014 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (raw == NULL)
1016 goto error;
1017 }
1018 else {
1019 raw = buf;
1020 Py_INCREF(raw);
1021 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001024 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001026 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (res == NULL)
1028 goto error;
1029 isatty = PyObject_IsTrue(res);
1030 Py_DECREF(res);
1031 if (isatty == -1)
1032 goto error;
1033 if (isatty || Py_UnbufferedStdioFlag)
1034 line_buffering = Py_True;
1035 else
1036 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 Py_CLEAR(raw);
1039 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001040
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001041#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001042 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1043 newlines to "\n".
1044 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1045 newline = NULL;
1046#else
1047 /* sys.stdin: split lines at "\n".
1048 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1049 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001050#endif
1051
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001052 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1053 buf, encoding, errors,
1054 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 Py_CLEAR(buf);
1056 if (stream == NULL)
1057 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (write_mode)
1060 mode = "w";
1061 else
1062 mode = "r";
1063 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001064 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 goto error;
1066 Py_CLEAR(text);
1067 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001068
1069error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 Py_XDECREF(buf);
1071 Py_XDECREF(stream);
1072 Py_XDECREF(text);
1073 Py_XDECREF(raw);
1074 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001075}
1076
Antoine Pitrou11942a52011-11-28 19:08:36 +01001077static int
1078is_valid_fd(int fd)
1079{
1080 int dummy_fd;
1081 if (fd < 0 || !_PyVerify_fd(fd))
1082 return 0;
1083 dummy_fd = dup(fd);
1084 if (dummy_fd < 0)
1085 return 0;
1086 close(dummy_fd);
1087 return 1;
1088}
1089
Georg Brandl1a3284e2007-12-02 09:40:06 +00001090/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001091static int
1092initstdio(void)
1093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyObject *iomod = NULL, *wrapper;
1095 PyObject *bimod = NULL;
1096 PyObject *m;
1097 PyObject *std = NULL;
1098 int status = 0, fd;
1099 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001100 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 /* Hack to avoid a nasty recursion issue when Python is invoked
1103 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1104 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1105 goto error;
1106 }
1107 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1110 goto error;
1111 }
1112 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 if (!(bimod = PyImport_ImportModule("builtins"))) {
1115 goto error;
1116 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (!(iomod = PyImport_ImportModule("io"))) {
1119 goto error;
1120 }
1121 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1122 goto error;
1123 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 /* Set builtins.open */
1126 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001127 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 goto error;
1129 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001130 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001131
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001132 encoding = _Py_StandardStreamEncoding;
1133 errors = _Py_StandardStreamErrors;
1134 if (!encoding || !errors) {
1135 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1136 if (pythonioencoding) {
1137 char *err;
1138 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1139 if (pythonioencoding == NULL) {
1140 PyErr_NoMemory();
1141 goto error;
1142 }
1143 err = strchr(pythonioencoding, ':');
1144 if (err) {
1145 *err = '\0';
1146 err++;
1147 if (*err && !errors) {
1148 errors = err;
1149 }
1150 }
1151 if (*pythonioencoding && !encoding) {
1152 encoding = pythonioencoding;
1153 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001154 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 /* Set sys.stdin */
1158 fd = fileno(stdin);
1159 /* Under some conditions stdin, stdout and stderr may not be connected
1160 * and fileno() may point to an invalid file descriptor. For example
1161 * GUI apps don't have valid standard streams by default.
1162 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001163 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 std = Py_None;
1165 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 }
1167 else {
1168 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1169 if (std == NULL)
1170 goto error;
1171 } /* if (fd < 0) */
1172 PySys_SetObject("__stdin__", std);
1173 PySys_SetObject("stdin", std);
1174 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 /* Set sys.stdout */
1177 fd = fileno(stdout);
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, 1, "<stdout>", encoding, errors);
1184 if (std == NULL)
1185 goto error;
1186 } /* if (fd < 0) */
1187 PySys_SetObject("__stdout__", std);
1188 PySys_SetObject("stdout", std);
1189 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001190
Guido van Rossum98297ee2007-11-06 21:34:58 +00001191#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 /* Set sys.stderr, replaces the preliminary stderr */
1193 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001194 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 std = Py_None;
1196 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 }
1198 else {
1199 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1200 if (std == NULL)
1201 goto error;
1202 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /* Same as hack above, pre-import stderr's codec to avoid recursion
1205 when import.c tries to write to stderr in verbose mode. */
1206 encoding_attr = PyObject_GetAttrString(std, "encoding");
1207 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001208 const char * std_encoding;
1209 std_encoding = _PyUnicode_AsString(encoding_attr);
1210 if (std_encoding != NULL) {
1211 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001212 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001214 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 }
1216 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001217
Victor Stinnerba308832013-07-22 23:55:19 +02001218 if (PySys_SetObject("__stderr__", std) < 0) {
1219 Py_DECREF(std);
1220 goto error;
1221 }
1222 if (PySys_SetObject("stderr", std) < 0) {
1223 Py_DECREF(std);
1224 goto error;
1225 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001227#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001230 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 status = -1;
1232 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001233
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001234 /* We won't need them anymore. */
1235 if (_Py_StandardStreamEncoding) {
1236 PyMem_RawFree(_Py_StandardStreamEncoding);
1237 _Py_StandardStreamEncoding = NULL;
1238 }
1239 if (_Py_StandardStreamErrors) {
1240 PyMem_RawFree(_Py_StandardStreamErrors);
1241 _Py_StandardStreamErrors = NULL;
1242 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001243 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 Py_XDECREF(bimod);
1245 Py_XDECREF(iomod);
1246 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001247}
1248
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001249/* Parse input from a file and execute it */
1250
1251int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001252PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (filename == NULL)
1256 filename = "???";
1257 if (Py_FdIsInteractive(fp, filename)) {
1258 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1259 if (closeit)
1260 fclose(fp);
1261 return err;
1262 }
1263 else
1264 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001265}
1266
1267int
Victor Stinner95701bd2013-11-06 18:41:07 +01001268PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001269{
Victor Stinner95701bd2013-11-06 18:41:07 +01001270 PyObject *filename, *v;
1271 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001273
Victor Stinner95701bd2013-11-06 18:41:07 +01001274 filename = PyUnicode_DecodeFSDefault(filename_str);
1275 if (filename == NULL) {
1276 PyErr_Print();
1277 return -1;
1278 }
1279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 if (flags == NULL) {
1281 flags = &local_flags;
1282 local_flags.cf_flags = 0;
1283 }
1284 v = PySys_GetObject("ps1");
1285 if (v == NULL) {
1286 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1287 Py_XDECREF(v);
1288 }
1289 v = PySys_GetObject("ps2");
1290 if (v == NULL) {
1291 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1292 Py_XDECREF(v);
1293 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001294 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 for (;;) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001296 ret = PyRun_InteractiveOneObject(fp, filename, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 PRINT_TOTAL_REFS();
Victor Stinner95701bd2013-11-06 18:41:07 +01001298 if (ret == E_EOF) {
1299 err = 0;
1300 break;
1301 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 /*
1303 if (ret == E_NOMEM)
Victor Stinner95701bd2013-11-06 18:41:07 +01001304 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 */
1306 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001307 Py_DECREF(filename);
1308 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001309}
1310
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001311/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001312static int PARSER_FLAGS(PyCompilerFlags *flags)
1313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 int parser_flags = 0;
1315 if (!flags)
1316 return 0;
1317 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1318 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1319 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1320 parser_flags |= PyPARSE_IGNORE_COOKIE;
1321 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1322 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1323 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001324}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001325
Thomas Wouters89f507f2006-12-13 04:49:30 +00001326#if 0
1327/* Keep an example of flags with future keyword support. */
1328#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1330 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1331 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1332 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001333#endif
1334
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001335int
Victor Stinner95701bd2013-11-06 18:41:07 +01001336PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001337{
Victor Stinner95701bd2013-11-06 18:41:07 +01001338 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 mod_ty mod;
1340 PyArena *arena;
1341 char *ps1 = "", *ps2 = "", *enc = NULL;
1342 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001343 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +01001344 _Py_IDENTIFIER(__main__);
1345
1346 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
1347 if (mod_name == NULL) {
1348 PyErr_Print();
1349 return -1;
1350 }
Tim Petersfe2127d2001-07-16 05:37:24 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001353 /* Fetch encoding from sys.stdin if possible. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 v = PySys_GetObject("stdin");
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001355 if (v && v != Py_None) {
1356 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1357 if (oenc)
1358 enc = _PyUnicode_AsString(oenc);
1359 if (!enc)
1360 PyErr_Clear();
1361 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 }
1363 v = PySys_GetObject("ps1");
1364 if (v != NULL) {
1365 v = PyObject_Str(v);
1366 if (v == NULL)
1367 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001368 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001370 if (ps1 == NULL) {
1371 PyErr_Clear();
1372 ps1 = "";
1373 }
1374 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 }
1376 w = PySys_GetObject("ps2");
1377 if (w != NULL) {
1378 w = PyObject_Str(w);
1379 if (w == NULL)
1380 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001381 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001383 if (ps2 == NULL) {
1384 PyErr_Clear();
1385 ps2 = "";
1386 }
1387 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 }
1389 arena = PyArena_New();
1390 if (arena == NULL) {
1391 Py_XDECREF(v);
1392 Py_XDECREF(w);
1393 Py_XDECREF(oenc);
1394 return -1;
1395 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001396 mod = PyParser_ASTFromFileObject(fp, filename, enc,
1397 Py_single_input, ps1, ps2,
1398 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_XDECREF(v);
1400 Py_XDECREF(w);
1401 Py_XDECREF(oenc);
1402 if (mod == NULL) {
1403 PyArena_Free(arena);
1404 if (errcode == E_EOF) {
1405 PyErr_Clear();
1406 return E_EOF;
1407 }
1408 PyErr_Print();
1409 return -1;
1410 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001411 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 if (m == NULL) {
1413 PyArena_Free(arena);
1414 return -1;
1415 }
1416 d = PyModule_GetDict(m);
1417 v = run_mod(mod, filename, d, d, flags, arena);
1418 PyArena_Free(arena);
1419 flush_io();
1420 if (v == NULL) {
1421 PyErr_Print();
1422 return -1;
1423 }
1424 Py_DECREF(v);
1425 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001426}
1427
Victor Stinner95701bd2013-11-06 18:41:07 +01001428int
1429PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
1430{
1431 PyObject *filename;
1432 int res;
1433
1434 filename = PyUnicode_DecodeFSDefault(filename_str);
1435 if (filename == NULL) {
1436 PyErr_Print();
1437 return -1;
1438 }
1439 res = PyRun_InteractiveOneObject(fp, filename, flags);
1440 Py_DECREF(filename);
1441 return res;
1442}
1443
1444
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001445/* Check whether a file maybe a pyc file: Look at the extension,
1446 the file type, and, if we may close it, at the first few bytes. */
1447
1448static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001449maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1452 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 /* Only look into the file if we are allowed to close it, since
1455 it then should also be seekable. */
1456 if (closeit) {
1457 /* Read only two bytes of the magic. If the file was opened in
1458 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1459 be read as they are on disk. */
1460 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1461 unsigned char buf[2];
1462 /* Mess: In case of -x, the stream is NOT at its start now,
1463 and ungetc() was used to push back the first newline,
1464 which makes the current stream position formally undefined,
1465 and a x-platform nightmare.
1466 Unfortunately, we have no direct way to know whether -x
1467 was specified. So we use a terrible hack: if the current
1468 stream position is not 0, we assume -x was specified, and
1469 give up. Bug 132850 on SourceForge spells out the
1470 hopelessness of trying anything else (fseek and ftell
1471 don't work predictably x-platform for text-mode files).
1472 */
1473 int ispyc = 0;
1474 if (ftell(fp) == 0) {
1475 if (fread(buf, 1, 2, fp) == 2 &&
1476 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1477 ispyc = 1;
1478 rewind(fp);
1479 }
1480 return ispyc;
1481 }
1482 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001483}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001484
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001485static int
1486set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001487{
1488 PyInterpreterState *interp;
1489 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001490 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001491 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001492
1493 filename_obj = PyUnicode_DecodeFSDefault(filename);
1494 if (filename_obj == NULL)
1495 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001496 /* Get current thread state and interpreter pointer */
1497 tstate = PyThreadState_GET();
1498 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001499 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1500 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001501 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001502 return -1;
1503 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001504 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001505 Py_DECREF(loader_type);
1506 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001507 return -1;
1508 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001509 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1510 result = -1;
1511 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001512 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001513 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001514}
1515
1516int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001517PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001519{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 PyObject *m, *d, *v;
1521 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001522 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001523 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 m = PyImport_AddModule("__main__");
1526 if (m == NULL)
1527 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001528 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 d = PyModule_GetDict(m);
1530 if (PyDict_GetItemString(d, "__file__") == NULL) {
1531 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001532 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001534 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1536 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001537 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001539 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1540 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001541 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001542 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 set_file_name = 1;
1544 Py_DECREF(f);
1545 }
1546 len = strlen(filename);
1547 ext = filename + len - (len > 4 ? 4 : 0);
1548 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001549 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 /* Try to run a pyc file. First, re-open in binary */
1551 if (closeit)
1552 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001553 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 goto done;
1556 }
1557 /* Turn on optimization if a .pyo file is given */
1558 if (strcmp(ext, ".pyo") == 0)
1559 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001560
1561 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1562 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1563 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001564 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001565 goto done;
1566 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001567 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1568 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001570 /* When running from stdin, leave __main__.__loader__ alone */
1571 if (strcmp(filename, "<stdin>") != 0 &&
1572 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1573 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1574 ret = -1;
1575 goto done;
1576 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1578 closeit, flags);
1579 }
1580 flush_io();
1581 if (v == NULL) {
1582 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 goto done;
1584 }
1585 Py_DECREF(v);
1586 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001587 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1589 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001590 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001592}
1593
1594int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001595PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 PyObject *m, *d, *v;
1598 m = PyImport_AddModule("__main__");
1599 if (m == NULL)
1600 return -1;
1601 d = PyModule_GetDict(m);
1602 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1603 if (v == NULL) {
1604 PyErr_Print();
1605 return -1;
1606 }
1607 Py_DECREF(v);
1608 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001609}
1610
Barry Warsaw035574d1997-08-29 22:07:17 +00001611static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001612parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 long hold;
1616 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001617 _Py_IDENTIFIER(msg);
1618 _Py_IDENTIFIER(filename);
1619 _Py_IDENTIFIER(lineno);
1620 _Py_IDENTIFIER(offset);
1621 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001622
Benjamin Peterson80d50422012-04-03 00:30:38 -04001623 *message = NULL;
1624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001626 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001627 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001629
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001630 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001631 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001633 if (v == Py_None) {
1634 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001636 }
1637 else {
1638 *filename = _PyUnicode_AsString(v);
1639 Py_DECREF(v);
1640 if (!*filename)
1641 goto finally;
1642 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001643
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001644 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001645 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 goto finally;
1647 hold = PyLong_AsLong(v);
1648 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 if (hold < 0 && PyErr_Occurred())
1650 goto finally;
1651 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001652
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001653 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001654 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 goto finally;
1656 if (v == Py_None) {
1657 *offset = -1;
1658 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 } else {
1660 hold = PyLong_AsLong(v);
1661 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 if (hold < 0 && PyErr_Occurred())
1663 goto finally;
1664 *offset = (int)hold;
1665 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001666
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001667 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001668 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001670 if (v == Py_None) {
1671 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001673 }
1674 else {
1675 *text = _PyUnicode_AsString(v);
1676 Py_DECREF(v);
1677 if (!*text)
1678 goto finally;
1679 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001681
1682finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001683 Py_XDECREF(*message);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001685}
1686
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001687void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001688PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001691}
1692
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001693static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001694print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 char *nl;
1697 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001698 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1699 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 for (;;) {
1701 nl = strchr(text, '\n');
1702 if (nl == NULL || nl-text >= offset)
1703 break;
1704 offset -= (int)(nl+1-text);
1705 text = nl+1;
1706 }
1707 while (*text == ' ' || *text == '\t') {
1708 text++;
1709 offset--;
1710 }
1711 }
1712 PyFile_WriteString(" ", f);
1713 PyFile_WriteString(text, f);
1714 if (*text == '\0' || text[strlen(text)-1] != '\n')
1715 PyFile_WriteString("\n", f);
1716 if (offset == -1)
1717 return;
1718 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001719 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001722}
1723
Guido van Rossum66e8e862001-03-23 17:54:43 +00001724static void
1725handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyObject *exception, *value, *tb;
1728 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 if (Py_InspectFlag)
1731 /* Don't exit if -i flag was given. This flag is set to 0
1732 * when entering interactive mode for inspecting. */
1733 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 PyErr_Fetch(&exception, &value, &tb);
1736 fflush(stdout);
1737 if (value == NULL || value == Py_None)
1738 goto done;
1739 if (PyExceptionInstance_Check(value)) {
1740 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001741 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001742 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (code) {
1744 Py_DECREF(value);
1745 value = code;
1746 if (value == Py_None)
1747 goto done;
1748 }
1749 /* If we failed to dig out the 'code' attribute,
1750 just let the else clause below print the error. */
1751 }
1752 if (PyLong_Check(value))
1753 exitcode = (int)PyLong_AsLong(value);
1754 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001755 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001756 if (sys_stderr != NULL && sys_stderr != Py_None) {
1757 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1758 } else {
1759 PyObject_Print(value, stderr, Py_PRINT_RAW);
1760 fflush(stderr);
1761 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PySys_WriteStderr("\n");
1763 exitcode = 1;
1764 }
Tim Peterscf615b52003-04-19 18:47:02 +00001765 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 /* Restore and clear the exception info, in order to properly decref
1767 * the exception, value, and traceback. If we just exit instead,
1768 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1769 * some finalizers from running.
1770 */
1771 PyErr_Restore(exception, value, tb);
1772 PyErr_Clear();
1773 Py_Exit(exitcode);
1774 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001775}
1776
1777void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001778PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1783 handle_system_exit();
1784 }
1785 PyErr_Fetch(&exception, &v, &tb);
1786 if (exception == NULL)
1787 return;
1788 PyErr_NormalizeException(&exception, &v, &tb);
1789 if (tb == NULL) {
1790 tb = Py_None;
1791 Py_INCREF(tb);
1792 }
1793 PyException_SetTraceback(v, tb);
1794 if (exception == NULL)
1795 return;
1796 /* Now we know v != NULL too */
1797 if (set_sys_last_vars) {
1798 PySys_SetObject("last_type", exception);
1799 PySys_SetObject("last_value", v);
1800 PySys_SetObject("last_traceback", tb);
1801 }
1802 hook = PySys_GetObject("excepthook");
1803 if (hook) {
1804 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1805 PyObject *result = PyEval_CallObject(hook, args);
1806 if (result == NULL) {
1807 PyObject *exception2, *v2, *tb2;
1808 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1809 handle_system_exit();
1810 }
1811 PyErr_Fetch(&exception2, &v2, &tb2);
1812 PyErr_NormalizeException(&exception2, &v2, &tb2);
1813 /* It should not be possible for exception2 or v2
1814 to be NULL. However PyErr_Display() can't
1815 tolerate NULLs, so just be safe. */
1816 if (exception2 == NULL) {
1817 exception2 = Py_None;
1818 Py_INCREF(exception2);
1819 }
1820 if (v2 == NULL) {
1821 v2 = Py_None;
1822 Py_INCREF(v2);
1823 }
1824 fflush(stdout);
1825 PySys_WriteStderr("Error in sys.excepthook:\n");
1826 PyErr_Display(exception2, v2, tb2);
1827 PySys_WriteStderr("\nOriginal exception was:\n");
1828 PyErr_Display(exception, v, tb);
1829 Py_DECREF(exception2);
1830 Py_DECREF(v2);
1831 Py_XDECREF(tb2);
1832 }
1833 Py_XDECREF(result);
1834 Py_XDECREF(args);
1835 } else {
1836 PySys_WriteStderr("sys.excepthook is missing\n");
1837 PyErr_Display(exception, v, tb);
1838 }
1839 Py_XDECREF(exception);
1840 Py_XDECREF(v);
1841 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001842}
1843
Benjamin Petersone6528212008-07-15 15:32:09 +00001844static void
1845print_exception(PyObject *f, PyObject *value)
1846{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 int err = 0;
1848 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001849 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 if (!PyExceptionInstance_Check(value)) {
1852 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1853 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1854 PyFile_WriteString(" found\n", f);
1855 return;
1856 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 Py_INCREF(value);
1859 fflush(stdout);
1860 type = (PyObject *) Py_TYPE(value);
1861 tb = PyException_GetTraceback(value);
1862 if (tb && tb != Py_None)
1863 err = PyTraceBack_Print(tb, f);
1864 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001865 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 {
1867 PyObject *message;
1868 const char *filename, *text;
1869 int lineno, offset;
1870 if (!parse_syntax_error(value, &message, &filename,
1871 &lineno, &offset, &text))
1872 PyErr_Clear();
1873 else {
1874 char buf[10];
1875 PyFile_WriteString(" File \"", f);
1876 if (filename == NULL)
1877 PyFile_WriteString("<string>", f);
1878 else
1879 PyFile_WriteString(filename, f);
1880 PyFile_WriteString("\", line ", f);
1881 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1882 PyFile_WriteString(buf, f);
1883 PyFile_WriteString("\n", f);
1884 if (text != NULL)
1885 print_error_text(f, offset, text);
1886 Py_DECREF(value);
1887 value = message;
1888 /* Can't be bothered to check all those
1889 PyFile_WriteString() calls */
1890 if (PyErr_Occurred())
1891 err = -1;
1892 }
1893 }
1894 if (err) {
1895 /* Don't do anything else */
1896 }
1897 else {
1898 PyObject* moduleName;
1899 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001900 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001901 assert(PyExceptionClass_Check(type));
1902 className = PyExceptionClass_Name(type);
1903 if (className != NULL) {
1904 char *dot = strrchr(className, '.');
1905 if (dot != NULL)
1906 className = dot+1;
1907 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001908
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001909 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1911 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001912 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 err = PyFile_WriteString("<unknown>", f);
1914 }
1915 else {
1916 char* modstr = _PyUnicode_AsString(moduleName);
1917 if (modstr && strcmp(modstr, "builtins"))
1918 {
1919 err = PyFile_WriteString(modstr, f);
1920 err += PyFile_WriteString(".", f);
1921 }
1922 Py_DECREF(moduleName);
1923 }
1924 if (err == 0) {
1925 if (className == NULL)
1926 err = PyFile_WriteString("<unknown>", f);
1927 else
1928 err = PyFile_WriteString(className, f);
1929 }
1930 }
1931 if (err == 0 && (value != Py_None)) {
1932 PyObject *s = PyObject_Str(value);
1933 /* only print colon if the str() of the
1934 object is not the empty string
1935 */
1936 if (s == NULL)
1937 err = -1;
1938 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001939 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 err = PyFile_WriteString(": ", f);
1941 if (err == 0)
1942 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1943 Py_XDECREF(s);
1944 }
1945 /* try to write a newline in any case */
1946 err += PyFile_WriteString("\n", f);
1947 Py_XDECREF(tb);
1948 Py_DECREF(value);
1949 /* If an error happened here, don't show it.
1950 XXX This is wrong, but too many callers rely on this behavior. */
1951 if (err != 0)
1952 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001953}
1954
1955static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 "\nThe above exception was the direct cause "
1957 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001958
1959static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 "\nDuring handling of the above exception, "
1961 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001962
1963static void
1964print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 int err = 0, res;
1967 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 if (seen != NULL) {
1970 /* Exception chaining */
1971 if (PySet_Add(seen, value) == -1)
1972 PyErr_Clear();
1973 else if (PyExceptionInstance_Check(value)) {
1974 cause = PyException_GetCause(value);
1975 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001976 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 res = PySet_Contains(seen, cause);
1978 if (res == -1)
1979 PyErr_Clear();
1980 if (res == 0) {
1981 print_exception_recursive(
1982 f, cause, seen);
1983 err |= PyFile_WriteString(
1984 cause_message, f);
1985 }
1986 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001987 else if (context &&
1988 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 res = PySet_Contains(seen, context);
1990 if (res == -1)
1991 PyErr_Clear();
1992 if (res == 0) {
1993 print_exception_recursive(
1994 f, context, seen);
1995 err |= PyFile_WriteString(
1996 context_message, f);
1997 }
1998 }
1999 Py_XDECREF(context);
2000 Py_XDECREF(cause);
2001 }
2002 }
2003 print_exception(f, value);
2004 if (err != 0)
2005 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002006}
2007
Thomas Wouters477c8d52006-05-27 19:21:47 +00002008void
2009PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 PyObject *seen;
2012 PyObject *f = PySys_GetObject("stderr");
Antoine Pitrou24201d42013-10-13 21:53:13 +02002013 if (PyExceptionInstance_Check(value)
2014 && tb != NULL && PyTraceBack_Check(tb)) {
2015 /* Put the traceback on the exception, otherwise it won't get
2016 displayed. See issue #18776. */
2017 PyObject *cur_tb = PyException_GetTraceback(value);
2018 if (cur_tb == NULL)
2019 PyException_SetTraceback(value, tb);
2020 else
2021 Py_DECREF(cur_tb);
2022 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 if (f == Py_None) {
2024 /* pass */
2025 }
2026 else if (f == NULL) {
2027 _PyObject_Dump(value);
2028 fprintf(stderr, "lost sys.stderr\n");
2029 }
2030 else {
2031 /* We choose to ignore seen being possibly NULL, and report
2032 at least the main exception (it could be a MemoryError).
2033 */
2034 seen = PySet_New(NULL);
2035 if (seen == NULL)
2036 PyErr_Clear();
2037 print_exception_recursive(f, value, seen);
2038 Py_XDECREF(seen);
2039 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002040}
2041
Guido van Rossum82598051997-03-05 00:20:32 +00002042PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002043PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 PyObject *ret = NULL;
2047 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002048 PyArena *arena;
2049 _Py_static_string(PyId_string, "<string>");
2050 PyObject *filename;
2051
2052 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2053 if (filename == NULL)
2054 return NULL;
2055
2056 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002057 if (arena == NULL)
2058 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002059
Victor Stinner95701bd2013-11-06 18:41:07 +01002060 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002062 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyArena_Free(arena);
2064 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002065}
2066
2067PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002068PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002070{
Victor Stinner95701bd2013-11-06 18:41:07 +01002071 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002073 PyArena *arena = NULL;
2074 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002075
Victor Stinner95701bd2013-11-06 18:41:07 +01002076 filename = PyUnicode_DecodeFSDefault(filename_str);
2077 if (filename == NULL)
2078 goto exit;
2079
2080 arena = PyArena_New();
2081 if (arena == NULL)
2082 goto exit;
2083
2084 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2085 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 if (closeit)
2087 fclose(fp);
2088 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002089 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 }
2091 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002092
2093exit:
2094 Py_XDECREF(filename);
2095 if (arena != NULL)
2096 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002098}
2099
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002100static void
2101flush_io(void)
2102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyObject *f, *r;
2104 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002105 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 /* Save the current exception */
2108 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 f = PySys_GetObject("stderr");
2111 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002112 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (r)
2114 Py_DECREF(r);
2115 else
2116 PyErr_Clear();
2117 }
2118 f = PySys_GetObject("stdout");
2119 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002120 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 if (r)
2122 Py_DECREF(r);
2123 else
2124 PyErr_Clear();
2125 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002128}
2129
Guido van Rossum82598051997-03-05 00:20:32 +00002130static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002131run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2132 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 PyCodeObject *co;
2135 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002136 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (co == NULL)
2138 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002139 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 Py_DECREF(co);
2141 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002142}
2143
Guido van Rossum82598051997-03-05 00:20:32 +00002144static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002145run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyCodeObject *co;
2149 PyObject *v;
2150 long magic;
2151 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 magic = PyMarshal_ReadLongFromFile(fp);
2154 if (magic != PyImport_GetMagicNumber()) {
2155 PyErr_SetString(PyExc_RuntimeError,
2156 "Bad magic number in .pyc file");
2157 return NULL;
2158 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002159 /* Skip mtime and size */
2160 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 (void) PyMarshal_ReadLongFromFile(fp);
2162 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 if (v == NULL || !PyCode_Check(v)) {
2164 Py_XDECREF(v);
2165 PyErr_SetString(PyExc_RuntimeError,
2166 "Bad code object in .pyc file");
2167 return NULL;
2168 }
2169 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002170 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 if (v && flags)
2172 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2173 Py_DECREF(co);
2174 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002175}
2176
Guido van Rossum82598051997-03-05 00:20:32 +00002177PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002178Py_CompileStringObject(const char *str, PyObject *filename, int start,
2179 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 PyCodeObject *co;
2182 mod_ty mod;
2183 PyArena *arena = PyArena_New();
2184 if (arena == NULL)
2185 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002186
Victor Stinner14e461d2013-08-26 22:28:21 +02002187 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 if (mod == NULL) {
2189 PyArena_Free(arena);
2190 return NULL;
2191 }
2192 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2193 PyObject *result = PyAST_mod2obj(mod);
2194 PyArena_Free(arena);
2195 return result;
2196 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002197 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 PyArena_Free(arena);
2199 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002200}
2201
Victor Stinner14e461d2013-08-26 22:28:21 +02002202PyObject *
2203Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2204 PyCompilerFlags *flags, int optimize)
2205{
2206 PyObject *filename, *co;
2207 filename = PyUnicode_DecodeFSDefault(filename_str);
2208 if (filename == NULL)
2209 return NULL;
2210 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2211 Py_DECREF(filename);
2212 return co;
2213}
2214
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002215/* For use in Py_LIMITED_API */
2216#undef Py_CompileString
2217PyObject *
2218PyCompileString(const char *str, const char *filename, int start)
2219{
2220 return Py_CompileStringFlags(str, filename, start, NULL);
2221}
2222
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002223struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002224Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 struct symtable *st;
2227 mod_ty mod;
2228 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002229 PyArena *arena;
2230
2231 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 if (arena == NULL)
2233 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002236 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 if (mod == NULL) {
2238 PyArena_Free(arena);
2239 return NULL;
2240 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002241 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 PyArena_Free(arena);
2243 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002244}
2245
Victor Stinner14e461d2013-08-26 22:28:21 +02002246struct symtable *
2247Py_SymtableString(const char *str, const char *filename_str, int start)
2248{
2249 PyObject *filename;
2250 struct symtable *st;
2251
2252 filename = PyUnicode_DecodeFSDefault(filename_str);
2253 if (filename == NULL)
2254 return NULL;
2255 st = Py_SymtableStringObject(str, filename, start);
2256 Py_DECREF(filename);
2257 return st;
2258}
2259
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002260/* Preferred access to parser is through AST. */
2261mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002262PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2263 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 mod_ty mod;
2266 PyCompilerFlags localflags;
2267 perrdetail err;
2268 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002269
Victor Stinner14e461d2013-08-26 22:28:21 +02002270 node *n = PyParser_ParseStringObject(s, filename,
2271 &_PyParser_Grammar, start, &err,
2272 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 if (flags == NULL) {
2274 localflags.cf_flags = 0;
2275 flags = &localflags;
2276 }
2277 if (n) {
2278 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002279 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002281 }
2282 else {
2283 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002284 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002286 err_free(&err);
2287 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002288}
2289
2290mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002291PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2292 PyCompilerFlags *flags, PyArena *arena)
2293{
2294 PyObject *filename;
2295 mod_ty mod;
2296 filename = PyUnicode_DecodeFSDefault(filename_str);
2297 if (filename == NULL)
2298 return NULL;
2299 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2300 Py_DECREF(filename);
2301 return mod;
2302}
2303
2304mod_ty
2305PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2306 int start, char *ps1,
2307 char *ps2, PyCompilerFlags *flags, int *errcode,
2308 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002310 mod_ty mod;
2311 PyCompilerFlags localflags;
2312 perrdetail err;
2313 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002314
Victor Stinner14e461d2013-08-26 22:28:21 +02002315 node *n = PyParser_ParseFileObject(fp, filename, enc,
2316 &_PyParser_Grammar,
2317 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 if (flags == NULL) {
2319 localflags.cf_flags = 0;
2320 flags = &localflags;
2321 }
2322 if (n) {
2323 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002324 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 }
2327 else {
2328 err_input(&err);
2329 if (errcode)
2330 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002331 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002333 err_free(&err);
2334 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002335}
2336
Victor Stinner14e461d2013-08-26 22:28:21 +02002337mod_ty
2338PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2339 int start, char *ps1,
2340 char *ps2, PyCompilerFlags *flags, int *errcode,
2341 PyArena *arena)
2342{
2343 mod_ty mod;
2344 PyObject *filename;
2345 filename = PyUnicode_DecodeFSDefault(filename_str);
2346 if (filename == NULL)
2347 return NULL;
2348 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2349 flags, errcode, arena);
2350 Py_DECREF(filename);
2351 return mod;
2352}
2353
Guido van Rossuma110aa61994-08-29 12:50:44 +00002354/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002355
Guido van Rossuma110aa61994-08-29 12:50:44 +00002356node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002357PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 perrdetail err;
2360 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2361 &_PyParser_Grammar,
2362 start, NULL, NULL, &err, flags);
2363 if (n == NULL)
2364 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002365 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002368}
2369
Guido van Rossuma110aa61994-08-29 12:50:44 +00002370/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002371
Guido van Rossuma110aa61994-08-29 12:50:44 +00002372node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002373PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 perrdetail err;
2376 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2377 start, &err, flags);
2378 if (n == NULL)
2379 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002380 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002382}
2383
2384node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002385PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 perrdetail err;
2389 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2390 &_PyParser_Grammar, start, &err, flags);
2391 if (n == NULL)
2392 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002393 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002395}
2396
2397node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002398PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002401}
2402
Guido van Rossum66ebd912003-04-17 16:02:26 +00002403/* May want to move a more generalized form of this to parsetok.c or
2404 even parser modules. */
2405
2406void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002407PyParser_ClearError(perrdetail *err)
2408{
2409 err_free(err);
2410}
2411
2412void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002413PyParser_SetError(perrdetail *err)
2414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002416}
2417
Victor Stinner7f2fee32011-04-05 00:39:01 +02002418static void
2419err_free(perrdetail *err)
2420{
2421 Py_CLEAR(err->filename);
2422}
2423
Guido van Rossuma110aa61994-08-29 12:50:44 +00002424/* Set the error appropriate to the given input error code (see errcode.h) */
2425
2426static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002427err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 PyObject *v, *w, *errtype, *errtext;
2430 PyObject *msg_obj = NULL;
2431 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 errtype = PyExc_SyntaxError;
2434 switch (err->error) {
2435 case E_ERROR:
2436 return;
2437 case E_SYNTAX:
2438 errtype = PyExc_IndentationError;
2439 if (err->expected == INDENT)
2440 msg = "expected an indented block";
2441 else if (err->token == INDENT)
2442 msg = "unexpected indent";
2443 else if (err->token == DEDENT)
2444 msg = "unexpected unindent";
2445 else {
2446 errtype = PyExc_SyntaxError;
2447 msg = "invalid syntax";
2448 }
2449 break;
2450 case E_TOKEN:
2451 msg = "invalid token";
2452 break;
2453 case E_EOFS:
2454 msg = "EOF while scanning triple-quoted string literal";
2455 break;
2456 case E_EOLS:
2457 msg = "EOL while scanning string literal";
2458 break;
2459 case E_INTR:
2460 if (!PyErr_Occurred())
2461 PyErr_SetNone(PyExc_KeyboardInterrupt);
2462 goto cleanup;
2463 case E_NOMEM:
2464 PyErr_NoMemory();
2465 goto cleanup;
2466 case E_EOF:
2467 msg = "unexpected EOF while parsing";
2468 break;
2469 case E_TABSPACE:
2470 errtype = PyExc_TabError;
2471 msg = "inconsistent use of tabs and spaces in indentation";
2472 break;
2473 case E_OVERFLOW:
2474 msg = "expression too long";
2475 break;
2476 case E_DEDENT:
2477 errtype = PyExc_IndentationError;
2478 msg = "unindent does not match any outer indentation level";
2479 break;
2480 case E_TOODEEP:
2481 errtype = PyExc_IndentationError;
2482 msg = "too many levels of indentation";
2483 break;
2484 case E_DECODE: {
2485 PyObject *type, *value, *tb;
2486 PyErr_Fetch(&type, &value, &tb);
2487 msg = "unknown decode error";
2488 if (value != NULL)
2489 msg_obj = PyObject_Str(value);
2490 Py_XDECREF(type);
2491 Py_XDECREF(value);
2492 Py_XDECREF(tb);
2493 break;
2494 }
2495 case E_LINECONT:
2496 msg = "unexpected character after line continuation character";
2497 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 case E_IDENTIFIER:
2500 msg = "invalid character in identifier";
2501 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002502 case E_BADSINGLE:
2503 msg = "multiple statements found while compiling a single statement";
2504 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 default:
2506 fprintf(stderr, "error=%d\n", err->error);
2507 msg = "unknown parsing error";
2508 break;
2509 }
2510 /* err->text may not be UTF-8 in case of decoding errors.
2511 Explicitly convert to an object. */
2512 if (!err->text) {
2513 errtext = Py_None;
2514 Py_INCREF(Py_None);
2515 } else {
2516 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2517 "replace");
2518 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002519 v = Py_BuildValue("(OiiN)", err->filename,
2520 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 if (v != NULL) {
2522 if (msg_obj)
2523 w = Py_BuildValue("(OO)", msg_obj, v);
2524 else
2525 w = Py_BuildValue("(sO)", msg, v);
2526 } else
2527 w = NULL;
2528 Py_XDECREF(v);
2529 PyErr_SetObject(errtype, w);
2530 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002531cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002532 Py_XDECREF(msg_obj);
2533 if (err->text != NULL) {
2534 PyObject_FREE(err->text);
2535 err->text = NULL;
2536 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002537}
2538
2539/* Print fatal error message and abort */
2540
2541void
Tim Peters7c321a82002-07-09 02:57:01 +00002542Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002543{
Victor Stinner024e37a2011-03-31 01:31:06 +02002544 const int fd = fileno(stderr);
2545 PyThreadState *tstate;
2546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 fprintf(stderr, "Fatal Python error: %s\n", msg);
2548 fflush(stderr); /* it helps in Windows debug build */
2549 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002550 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002552 else {
2553 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2554 if (tstate != NULL) {
2555 fputc('\n', stderr);
2556 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002557 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002558 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002559 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002560 }
2561
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002562#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 {
2564 size_t len = strlen(msg);
2565 WCHAR* buffer;
2566 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 /* Convert the message to wchar_t. This uses a simple one-to-one
2569 conversion, assuming that the this error message actually uses ASCII
2570 only. If this ceases to be true, we will have to convert. */
2571 buffer = alloca( (len+1) * (sizeof *buffer));
2572 for( i=0; i<=len; ++i)
2573 buffer[i] = msg[i];
2574 OutputDebugStringW(L"Fatal Python error: ");
2575 OutputDebugStringW(buffer);
2576 OutputDebugStringW(L"\n");
2577 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002578#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002580#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002581#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002583}
2584
2585/* Clean up and exit */
2586
Guido van Rossuma110aa61994-08-29 12:50:44 +00002587#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002588#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002589#endif
2590
Collin Winter670e6922007-03-21 02:57:17 +00002591static void (*pyexitfunc)(void) = NULL;
2592/* For the atexit module. */
2593void _Py_PyAtExit(void (*func)(void))
2594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002596}
2597
2598static void
2599call_py_exitfuncs(void)
2600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 if (pyexitfunc == NULL)
2602 return;
Collin Winter670e6922007-03-21 02:57:17 +00002603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 (*pyexitfunc)();
2605 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002606}
2607
Antoine Pitrou011bd622009-10-20 21:52:47 +00002608/* Wait until threading._shutdown completes, provided
2609 the threading module was imported in the first place.
2610 The shutdown routine will wait until all non-daemon
2611 "threading" threads have completed. */
2612static void
2613wait_for_thread_shutdown(void)
2614{
2615#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002616 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 PyObject *result;
2618 PyThreadState *tstate = PyThreadState_GET();
2619 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2620 "threading");
2621 if (threading == NULL) {
2622 /* threading not imported */
2623 PyErr_Clear();
2624 return;
2625 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002626 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 if (result == NULL) {
2628 PyErr_WriteUnraisable(threading);
2629 }
2630 else {
2631 Py_DECREF(result);
2632 }
2633 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002634#endif
2635}
2636
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002637#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002638static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002639static int nexitfuncs = 0;
2640
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002641int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 if (nexitfuncs >= NEXITFUNCS)
2644 return -1;
2645 exitfuncs[nexitfuncs++] = func;
2646 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002647}
2648
Guido van Rossumcc283f51997-08-05 02:22:03 +00002649static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002650call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 while (nexitfuncs > 0)
2653 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002655 fflush(stdout);
2656 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002657}
2658
2659void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002660Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002665}
2666
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002667static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002668initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002669{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002670#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002672#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002673#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002674 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002675#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002676#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002677 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002678#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002680 if (PyErr_Occurred()) {
2681 Py_FatalError("Py_Initialize: can't import signal");
2682 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002683}
2684
Guido van Rossum7433b121997-02-14 19:45:36 +00002685
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002686/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2687 *
2688 * All of the code in this function must only use async-signal-safe functions,
2689 * listed at `man 7 signal` or
2690 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2691 */
2692void
2693_Py_RestoreSignals(void)
2694{
2695#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002697#endif
2698#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002700#endif
2701#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002703#endif
2704}
2705
2706
Guido van Rossum7433b121997-02-14 19:45:36 +00002707/*
2708 * The file descriptor fd is considered ``interactive'' if either
2709 * a) isatty(fd) is TRUE, or
2710 * b) the -i flag was given, and the filename associated with
2711 * the descriptor is NULL or "<stdin>" or "???".
2712 */
2713int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002714Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 if (isatty((int)fileno(fp)))
2717 return 1;
2718 if (!Py_InteractiveFlag)
2719 return 0;
2720 return (filename == NULL) ||
2721 (strcmp(filename, "<stdin>") == 0) ||
2722 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002723}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002724
2725
Tim Petersd08e3822003-04-17 15:24:21 +00002726#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002727#if defined(WIN32) && defined(_MSC_VER)
2728
2729/* Stack checking for Microsoft C */
2730
2731#include <malloc.h>
2732#include <excpt.h>
2733
Fred Drakee8de31c2000-08-31 05:38:39 +00002734/*
2735 * Return non-zero when we run out of memory on the stack; zero otherwise.
2736 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002737int
Fred Drake399739f2000-08-31 05:52:44 +00002738PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 __try {
2741 /* alloca throws a stack overflow exception if there's
2742 not enough space left on the stack */
2743 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2744 return 0;
2745 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2746 EXCEPTION_EXECUTE_HANDLER :
2747 EXCEPTION_CONTINUE_SEARCH) {
2748 int errcode = _resetstkoflw();
2749 if (errcode == 0)
2750 {
2751 Py_FatalError("Could not reset the stack!");
2752 }
2753 }
2754 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002755}
2756
2757#endif /* WIN32 && _MSC_VER */
2758
2759/* Alternate implementations can be added here... */
2760
2761#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002762
2763
2764/* Wrappers around sigaction() or signal(). */
2765
2766PyOS_sighandler_t
2767PyOS_getsig(int sig)
2768{
2769#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 struct sigaction context;
2771 if (sigaction(sig, NULL, &context) == -1)
2772 return SIG_ERR;
2773 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002774#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002776/* Special signal handling for the secure CRT in Visual Studio 2005 */
2777#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 switch (sig) {
2779 /* Only these signals are valid */
2780 case SIGINT:
2781 case SIGILL:
2782 case SIGFPE:
2783 case SIGSEGV:
2784 case SIGTERM:
2785 case SIGBREAK:
2786 case SIGABRT:
2787 break;
2788 /* Don't call signal() with other values or it will assert */
2789 default:
2790 return SIG_ERR;
2791 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002792#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 handler = signal(sig, SIG_IGN);
2794 if (handler != SIG_ERR)
2795 signal(sig, handler);
2796 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002797#endif
2798}
2799
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002800/*
2801 * All of the code in this function must only use async-signal-safe functions,
2802 * listed at `man 7 signal` or
2803 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2804 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002805PyOS_sighandler_t
2806PyOS_setsig(int sig, PyOS_sighandler_t handler)
2807{
2808#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 /* Some code in Modules/signalmodule.c depends on sigaction() being
2810 * used here if HAVE_SIGACTION is defined. Fix that if this code
2811 * changes to invalidate that assumption.
2812 */
2813 struct sigaction context, ocontext;
2814 context.sa_handler = handler;
2815 sigemptyset(&context.sa_mask);
2816 context.sa_flags = 0;
2817 if (sigaction(sig, &context, &ocontext) == -1)
2818 return SIG_ERR;
2819 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002820#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 PyOS_sighandler_t oldhandler;
2822 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002823#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002825#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002827#endif
2828}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002829
2830/* Deprecated C API functions still provided for binary compatiblity */
2831
2832#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002833PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002834PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002837}
2838
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002839#undef PyParser_SimpleParseString
2840PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002841PyParser_SimpleParseString(const char *str, int start)
2842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002844}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002845
2846#undef PyRun_AnyFile
2847PyAPI_FUNC(int)
2848PyRun_AnyFile(FILE *fp, const char *name)
2849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002851}
2852
2853#undef PyRun_AnyFileEx
2854PyAPI_FUNC(int)
2855PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002858}
2859
2860#undef PyRun_AnyFileFlags
2861PyAPI_FUNC(int)
2862PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002864 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002865}
2866
2867#undef PyRun_File
2868PyAPI_FUNC(PyObject *)
2869PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002872}
2873
2874#undef PyRun_FileEx
2875PyAPI_FUNC(PyObject *)
2876PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002878 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002879}
2880
2881#undef PyRun_FileFlags
2882PyAPI_FUNC(PyObject *)
2883PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002886 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002887}
2888
2889#undef PyRun_SimpleFile
2890PyAPI_FUNC(int)
2891PyRun_SimpleFile(FILE *f, const char *p)
2892{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002893 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002894}
2895
2896#undef PyRun_SimpleFileEx
2897PyAPI_FUNC(int)
2898PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2899{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002901}
2902
2903
2904#undef PyRun_String
2905PyAPI_FUNC(PyObject *)
2906PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002909}
2910
2911#undef PyRun_SimpleString
2912PyAPI_FUNC(int)
2913PyRun_SimpleString(const char *s)
2914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002916}
2917
2918#undef Py_CompileString
2919PyAPI_FUNC(PyObject *)
2920Py_CompileString(const char *str, const char *p, int s)
2921{
Georg Brandl8334fd92010-12-04 10:26:46 +00002922 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2923}
2924
2925#undef Py_CompileStringFlags
2926PyAPI_FUNC(PyObject *)
2927Py_CompileStringFlags(const char *str, const char *p, int s,
2928 PyCompilerFlags *flags)
2929{
2930 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002931}
2932
2933#undef PyRun_InteractiveOne
2934PyAPI_FUNC(int)
2935PyRun_InteractiveOne(FILE *f, const char *p)
2936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002937 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002938}
2939
2940#undef PyRun_InteractiveLoop
2941PyAPI_FUNC(int)
2942PyRun_InteractiveLoop(FILE *f, const char *p)
2943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002945}
2946
2947#ifdef __cplusplus
2948}
2949#endif