blob: 922446ecf6c531deac144b8d4656653372248ca3 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Victor Stinnerbd303c12013-11-07 23:07:29 +010038_Py_IDENTIFIER(builtins);
Victor Stinner09054372013-11-06 22:41:44 +010039_Py_IDENTIFIER(excepthook);
Victor Stinnerbd303c12013-11-07 23:07:29 +010040_Py_IDENTIFIER(last_traceback);
Victor Stinner09054372013-11-06 22:41:44 +010041_Py_IDENTIFIER(last_type);
42_Py_IDENTIFIER(last_value);
Victor Stinnerbd303c12013-11-07 23:07:29 +010043_Py_IDENTIFIER(ps1);
44_Py_IDENTIFIER(ps2);
45_Py_IDENTIFIER(stdin);
46_Py_IDENTIFIER(stdout);
47_Py_IDENTIFIER(stderr);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +010048_Py_static_string(PyId_string, "<string>");
Victor Stinner09054372013-11-06 22:41:44 +010049
Ezio Melotti1f8898a2013-03-26 01:59:56 +020050#ifdef Py_REF_DEBUG
Antoine Pitrou208ac5c2013-04-24 20:17:53 +020051static
52void _print_total_refs(void) {
Victor Stinner4ee41c52013-11-06 18:28:21 +010053 PyObject *xoptions, *value;
54 _Py_IDENTIFIER(showrefcount);
55
Ezio Melotti1f8898a2013-03-26 01:59:56 +020056 xoptions = PySys_GetXOptions();
57 if (xoptions == NULL)
58 return;
Victor Stinner4ee41c52013-11-06 18:28:21 +010059 value = _PyDict_GetItemId(xoptions, &PyId_showrefcount);
Ezio Melotti1f8898a2013-03-26 01:59:56 +020060 if (value == Py_True)
61 fprintf(stderr,
62 "[%" PY_FORMAT_SIZE_T "d refs, "
63 "%" PY_FORMAT_SIZE_T "d blocks]\n",
64 _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
65}
66#endif
67
Neal Norwitz4281cef2006-03-04 19:58:13 +000068#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000069#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000070#else /* Py_REF_DEBUG */
Ezio Melotti1f8898a2013-03-26 01:59:56 +020071#define PRINT_TOTAL_REFS() _print_total_refs()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000072#endif
73
74#ifdef __cplusplus
75extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000076#endif
77
Martin v. Löwis790465f2008-04-05 20:41:37 +000078extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000079
Guido van Rossum82598051997-03-05 00:20:32 +000080extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000081
Guido van Rossumb73cc041993-11-01 16:28:59 +000082/* Forward */
Nick Coghlan85e729e2012-07-15 18:09:52 +100083static void initmain(PyInterpreterState *interp);
Victor Stinner793b5312011-04-27 00:24:21 +020084static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000085static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000086static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000087static void flush_io(void);
Victor Stinner95701bd2013-11-06 18:41:07 +010088static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000090static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000092static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020093static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000094static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000095static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000096static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000097static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +020098extern int _PyUnicode_Init(void);
Victor Stinner26f91992013-07-17 01:22:45 +020099extern int _PyStructSequence_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000100extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +0000101extern int _PyLong_Init(void);
102extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +0200103extern int _PyFaulthandler_Init(void);
104extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +0000105
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000106#ifdef WITH_THREAD
107extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
108extern void _PyGILState_Fini(void);
109#endif /* WITH_THREAD */
110
Guido van Rossum82598051997-03-05 00:20:32 +0000111int Py_DebugFlag; /* Needed by parser.c */
112int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +0000113int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +0000114int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +0200115int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000116int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000117int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +0000118int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +0000119int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +0000120int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000121int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +0000122int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +0000123int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100124int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Christian Heimesad73a9c2013-08-10 16:36:18 +0200125int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000126
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200127PyThreadState *_Py_Finalizing = NULL;
128
Christian Heimes49e61802013-10-22 10:22:29 +0200129/* Hack to force loading of object files */
130int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
131 PyOS_mystrnicmp; /* Python/pystrcmp.o */
132
Christian Heimes33fe8092008-04-13 13:53:33 +0000133/* PyModule_GetWarningsModule is no longer necessary as of 2.6
134since _warnings is builtin. This API should not be used. */
135PyObject *
136PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000139}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000140
Guido van Rossum25ce5661997-08-02 03:10:38 +0000141static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000142
Thomas Wouters7e474022000-07-16 12:04:32 +0000143/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000144
145int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000146Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000149}
150
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000151/* Helper to allow an embedding application to override the normal
152 * mechanism that attempts to figure out an appropriate IO encoding
153 */
154
155static char *_Py_StandardStreamEncoding = NULL;
156static char *_Py_StandardStreamErrors = NULL;
157
158int
159Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
160{
161 if (Py_IsInitialized()) {
162 /* This is too late to have any effect */
163 return -1;
164 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000165 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
166 * initialised yet.
167 *
168 * However, the raw memory allocators are initialised appropriately
169 * as C static variables, so _PyMem_RawStrdup is OK even though
170 * Py_Initialize hasn't been called yet.
171 */
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000172 if (encoding) {
173 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
174 if (!_Py_StandardStreamEncoding) {
Nick Coghlan1805a622013-10-18 23:11:47 +1000175 return -2;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000176 }
177 }
178 if (errors) {
179 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
180 if (!_Py_StandardStreamErrors) {
181 if (_Py_StandardStreamEncoding) {
182 PyMem_RawFree(_Py_StandardStreamEncoding);
183 }
Nick Coghlan1805a622013-10-18 23:11:47 +1000184 return -3;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000185 }
186 }
187 return 0;
188}
189
Guido van Rossum25ce5661997-08-02 03:10:38 +0000190/* Global initializations. Can be undone by Py_Finalize(). Don't
191 call this twice without an intervening Py_Finalize() call. When
192 initializations fail, a fatal error is issued and the function does
193 not return. On return, the first thread and interpreter state have
194 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000195
Guido van Rossum25ce5661997-08-02 03:10:38 +0000196 Locking: you must hold the interpreter lock while calling this.
197 (If the lock has not yet been initialized, that's equivalent to
198 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000199
Guido van Rossum25ce5661997-08-02 03:10:38 +0000200*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000201
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000202static int
203add_flag(int flag, const char *envs)
204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 int env = atoi(envs);
206 if (flag < env)
207 flag = env;
208 if (flag < 1)
209 flag = 1;
210 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000211}
212
Christian Heimes5833a2f2008-10-30 21:40:04 +0000213static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000214get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000215{
Victor Stinner94908bb2010-08-18 21:23:25 +0000216 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000217 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200218 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000219
Victor Stinner94908bb2010-08-18 21:23:25 +0000220 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (!codec)
222 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000223
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200224 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 Py_CLEAR(codec);
226 if (!name)
227 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000228
Victor Stinner94908bb2010-08-18 21:23:25 +0000229 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100230 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000231 goto error;
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200232 name_str = _PyMem_RawStrdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000234 if (name_str == NULL) {
235 PyErr_NoMemory();
236 return NULL;
237 }
238 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000239
240error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000242 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000244}
Victor Stinner94908bb2010-08-18 21:23:25 +0000245
Victor Stinner94908bb2010-08-18 21:23:25 +0000246static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200247get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000248{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200249#ifdef MS_WINDOWS
250 char codepage[100];
251 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
252 return get_codec_name(codepage);
253#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000254 char* codeset = nl_langinfo(CODESET);
255 if (!codeset || codeset[0] == '\0') {
256 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
257 return NULL;
258 }
259 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200260#else
261 PyErr_SetNone(PyExc_NotImplementedError);
262 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000263#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200264}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000265
Brett Cannonfd074152012-04-14 14:10:13 -0400266static void
267import_init(PyInterpreterState *interp, PyObject *sysmod)
268{
269 PyObject *importlib;
270 PyObject *impmod;
271 PyObject *sys_modules;
272 PyObject *value;
273
274 /* Import _importlib through its frozen version, _frozen_importlib. */
Brett Cannonfd074152012-04-14 14:10:13 -0400275 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
276 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
277 }
278 else if (Py_VerboseFlag) {
279 PySys_FormatStderr("import _frozen_importlib # frozen\n");
280 }
281 importlib = PyImport_AddModule("_frozen_importlib");
282 if (importlib == NULL) {
283 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
284 "sys.modules");
285 }
286 interp->importlib = importlib;
287 Py_INCREF(interp->importlib);
288
289 /* Install _importlib as __import__ */
290 impmod = PyInit_imp();
291 if (impmod == NULL) {
292 Py_FatalError("Py_Initialize: can't import imp");
293 }
294 else if (Py_VerboseFlag) {
295 PySys_FormatStderr("import imp # builtin\n");
296 }
297 sys_modules = PyImport_GetModuleDict();
298 if (Py_VerboseFlag) {
299 PySys_FormatStderr("import sys # builtin\n");
300 }
Brett Cannon6f44d662012-04-15 16:08:47 -0400301 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
302 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
Brett Cannonfd074152012-04-14 14:10:13 -0400303 }
304
Brett Cannone0d88a12012-04-25 20:54:04 -0400305 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400306 if (value == NULL) {
307 PyErr_Print();
308 Py_FatalError("Py_Initialize: importlib install failed");
309 }
310 Py_DECREF(value);
Brett Cannonfc9ca272012-04-15 01:35:05 -0400311 Py_DECREF(impmod);
Brett Cannonfd074152012-04-14 14:10:13 -0400312
313 _PyImportZip_Init();
314}
315
316
Guido van Rossuma027efa1997-05-05 20:56:21 +0000317void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200318_Py_InitializeEx_Private(int install_sigs, int install_importlib)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 PyInterpreterState *interp;
321 PyThreadState *tstate;
322 PyObject *bimod, *sysmod, *pstderr;
323 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 if (initialized)
327 return;
328 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200329 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000330
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000331#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332 /* Set up the LC_CTYPE locale, so we can obtain
333 the locale's charset without having to switch
334 locales. */
335 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000336#endif
337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
339 Py_DebugFlag = add_flag(Py_DebugFlag, p);
340 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
341 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
342 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
343 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
344 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
345 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100346 /* The variable is only tested for existence here; _PyRandom_Init will
347 check its value further. */
348 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
349 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
350
351 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 interp = PyInterpreterState_New();
354 if (interp == NULL)
355 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 tstate = PyThreadState_New(interp);
358 if (tstate == NULL)
359 Py_FatalError("Py_Initialize: can't make first thread");
360 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000361
Victor Stinner6961bd62010-08-17 22:26:51 +0000362#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000363 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
364 destroying the GIL might fail when it is being referenced from
365 another running thread (see issue #9901).
366 Instead we destroy the previously created GIL here, which ensures
367 that we can call Py_Initialize / Py_Finalize multiple times. */
368 _PyEval_FiniThreads();
369
370 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000371 _PyGILState_Init(interp, tstate);
372#endif /* WITH_THREAD */
373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000375
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 if (!_PyFrame_Init())
377 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (!_PyLong_Init())
380 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (!PyByteArray_Init())
383 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000384
Victor Stinner1c8f0592013-07-22 22:24:54 +0200385 if (!_PyFloat_Init())
386 Py_FatalError("Py_Initialize: can't init float");
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 interp->modules = PyDict_New();
389 if (interp->modules == NULL)
390 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200393 if (_PyUnicode_Init() < 0)
394 Py_FatalError("Py_Initialize: can't initialize unicode");
Victor Stinner26f91992013-07-17 01:22:45 +0200395 if (_PyStructSequence_Init() < 0)
396 Py_FatalError("Py_Initialize: can't initialize structseq");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 bimod = _PyBuiltin_Init();
399 if (bimod == NULL)
400 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000401 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 interp->builtins = PyModule_GetDict(bimod);
403 if (interp->builtins == NULL)
404 Py_FatalError("Py_Initialize: can't initialize builtins dict");
405 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400408 _PyExc_Init(bimod);
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 sysmod = _PySys_Init();
411 if (sysmod == NULL)
412 Py_FatalError("Py_Initialize: can't initialize sys");
413 interp->sysdict = PyModule_GetDict(sysmod);
414 if (interp->sysdict == NULL)
415 Py_FatalError("Py_Initialize: can't initialize sys dict");
416 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000417 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 PySys_SetPath(Py_GetPath());
419 PyDict_SetItemString(interp->sysdict, "modules",
420 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 /* Set up a preliminary stderr printer until we have enough
423 infrastructure for the io module in place. */
424 pstderr = PyFile_NewStdPrinter(fileno(stderr));
425 if (pstderr == NULL)
426 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100427 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000429 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000434
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000435 /* Initialize _warnings. */
436 _PyWarnings_Init();
437
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200438 if (!install_importlib)
439 return;
440
Brett Cannonfd074152012-04-14 14:10:13 -0400441 import_init(interp, sysmod);
442
Victor Stinnerd5698cb2012-07-31 02:55:49 +0200443 /* initialize the faulthandler module */
444 if (_PyFaulthandler_Init())
445 Py_FatalError("Py_Initialize: can't initialize faulthandler");
446
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000447 _PyTime_Init();
448
Victor Stinner793b5312011-04-27 00:24:21 +0200449 if (initfsencoding(interp) < 0)
450 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (install_sigs)
453 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000454
Nick Coghlan85e729e2012-07-15 18:09:52 +1000455 initmain(interp); /* Module __main__ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (initstdio() < 0)
457 Py_FatalError(
458 "Py_Initialize: can't initialize sys standard streams");
459
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000460 /* Initialize warnings. */
461 if (PySys_HasWarnOptions()) {
462 PyObject *warnings_module = PyImport_ImportModule("warnings");
463 if (warnings_module == NULL) {
464 fprintf(stderr, "'import warnings' failed; traceback:\n");
465 PyErr_Print();
466 }
467 Py_XDECREF(warnings_module);
468 }
469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (!Py_NoSiteFlag)
471 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000472}
473
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000474void
Antoine Pitroue67f48c2012-06-19 22:29:35 +0200475Py_InitializeEx(int install_sigs)
476{
477 _Py_InitializeEx_Private(install_sigs, 1);
478}
479
480void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000481Py_Initialize(void)
482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000484}
485
486
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000487#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000488extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000489#endif
490
Guido van Rossume8432ac2007-07-09 15:04:50 +0000491/* Flush stdout and stderr */
492
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100493static int
494file_is_closed(PyObject *fobj)
495{
496 int r;
497 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
498 if (tmp == NULL) {
499 PyErr_Clear();
500 return 0;
501 }
502 r = PyObject_IsTrue(tmp);
503 Py_DECREF(tmp);
504 if (r < 0)
505 PyErr_Clear();
506 return r > 0;
507}
508
Neal Norwitz2bad9702007-08-27 06:19:22 +0000509static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000510flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000511{
Victor Stinnerbd303c12013-11-07 23:07:29 +0100512 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
513 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200515 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000516
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100517 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200518 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000520 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 else
522 Py_DECREF(tmp);
523 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000524
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100525 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200526 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 if (tmp == NULL)
528 PyErr_Clear();
529 else
530 Py_DECREF(tmp);
531 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000532}
533
Guido van Rossum25ce5661997-08-02 03:10:38 +0000534/* Undo the effect of Py_Initialize().
535
536 Beware: if multiple interpreter and/or thread states exist, these
537 are not wiped out; only the current thread and interpreter state
538 are deleted. But since everything else is deleted, those other
539 interpreter and thread states should no longer be used.
540
541 (XXX We should do better, e.g. wipe out all interpreters and
542 threads.)
543
544 Locking: as above.
545
546*/
547
548void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000549Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 PyInterpreterState *interp;
552 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (!initialized)
555 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 /* The interpreter is still entirely intact at this point, and the
560 * exit funcs may be relying on that. In particular, if some thread
561 * or exit func is still waiting to do an import, the import machinery
562 * expects Py_IsInitialized() to return true. So don't say the
563 * interpreter is uninitialized until after the exit funcs have run.
564 * Note that Threading.py uses an exit func to do a join on all the
565 * threads created thru it, so this also protects pending imports in
566 * the threads created via Threading.
567 */
568 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 /* Get current thread state and interpreter pointer */
571 tstate = PyThreadState_GET();
572 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200574 /* Remaining threads (e.g. daemon threads) will automatically exit
575 after taking the GIL (in PyEval_RestoreThread()). */
576 _Py_Finalizing = tstate;
577 initialized = 0;
578
579 /* Flush stdout+stderr */
580 flush_std_files();
581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 /* Disable signal handling */
583 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 /* Collect garbage. This may call finalizers; it's nice to call these
586 * before all modules are destroyed.
587 * XXX If a __del__ or weakref callback is triggered here, and tries to
588 * XXX import a module, bad things can happen, because Python no
589 * XXX longer believes it's initialized.
590 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
591 * XXX is easy to provoke that way. I've also seen, e.g.,
592 * XXX Exception exceptions.ImportError: 'No module named sha'
593 * XXX in <function callback at 0x008F5718> ignored
594 * XXX but I'm unclear on exactly how that one happens. In any case,
595 * XXX I haven't seen a real-life report of either of these.
596 */
597 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000598#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 /* With COUNT_ALLOCS, it helps to run GC multiple times:
600 each collection might release some types from the type
601 list, so they become garbage. */
602 while (PyGC_Collect() > 0)
603 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000604#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 /* Destroy all modules */
606 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* Flush stdout+stderr (again, in case more was printed) */
609 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100612 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 * XXX This is disabled because it caused too many problems. If
614 * XXX a __del__ or weakref callback triggers here, Python code has
615 * XXX a hard time running, because even the sys module has been
616 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
617 * XXX One symptom is a sequence of information-free messages
618 * XXX coming from threads (if a __del__ or callback is invoked,
619 * XXX other threads can execute too, and any exception they encounter
620 * XXX triggers a comedy of errors as subsystem after subsystem
621 * XXX fails to find what it *expects* to find in sys to help report
622 * XXX the exception and consequent unexpected failures). I've also
623 * XXX seen segfaults then, after adding print statements to the
624 * XXX Python code getting called.
625 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000626#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000628#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
631 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000632
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200633 /* Cleanup typeobject.c's internal caches. */
634 _PyType_Fini();
635
Victor Stinner024e37a2011-03-31 01:31:06 +0200636 /* unload faulthandler module */
637 _PyFaulthandler_Fini();
638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000640#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000642#endif
643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000645
Tim Peters9cf25ce2003-04-17 15:21:01 +0000646#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 /* Display all objects still alive -- this can invoke arbitrary
648 * __repr__ overrides, so requires a mostly-intact interpreter.
649 * Alas, a lot of stuff may still be alive now that will be cleaned
650 * up later.
651 */
652 if (Py_GETENV("PYTHONDUMPREFS"))
653 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000654#endif /* Py_TRACE_REFS */
655
Antoine Pitroufd417cc2013-05-05 08:12:42 +0200656 /* Clear interpreter state and all thread states. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 /* Now we decref the exception classes. After this point nothing
660 can raise an exception. That's okay, because each Fini() method
661 below has been checked to make sure no exceptions are ever
662 raised.
663 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000664
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 /* Sundry finalizers */
668 PyMethod_Fini();
669 PyFrame_Fini();
670 PyCFunction_Fini();
671 PyTuple_Fini();
672 PyList_Fini();
673 PySet_Fini();
674 PyBytes_Fini();
675 PyByteArray_Fini();
676 PyLong_Fini();
677 PyFloat_Fini();
678 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100679 PySlice_Fini();
Antoine Pitrou5f454a02013-05-06 21:15:57 +0200680 _PyGC_Fini();
Antoine Pitrou4879a962013-08-31 00:26:02 +0200681 _PyRandom_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 /* Cleanup Unicode implementation */
684 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000685
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000687 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +0200688 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 Py_FileSystemDefaultEncoding = NULL;
690 }
Christian Heimesc8967002007-11-30 10:18:26 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 /* XXX Still allocated:
693 - various static ad-hoc pointers to interned strings
694 - int and float free list blocks
695 - whatever various modules and libraries allocate
696 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000699
Victor Stinner51fa4582013-07-07 15:50:49 +0200700 /* Cleanup auto-thread-state */
701#ifdef WITH_THREAD
702 _PyGILState_Fini();
703#endif /* WITH_THREAD */
704
705 /* Delete current thread. After this, many C API calls become crashy. */
706 PyThreadState_Swap(NULL);
707 PyInterpreterState_Delete(interp);
708
Tim Peters269b2a62003-04-17 19:52:29 +0000709#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 /* Display addresses (& refcnts) of all objects still alive.
711 * An address can be used to find the repr of the object, printed
712 * above by _Py_PrintReferences.
713 */
714 if (Py_GETENV("PYTHONDUMPREFS"))
715 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000716#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000717#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 if (Py_GETENV("PYTHONMALLOCSTATS"))
David Malcolm49526f42012-06-22 14:55:41 -0400719 _PyObject_DebugMallocStats(stderr);
Tim Peters0e871182002-04-13 08:29:14 +0000720#endif
721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000723}
724
725/* Create and initialize a new interpreter and thread, and return the
726 new thread. This requires that Py_Initialize() has been called
727 first.
728
729 Unsuccessful initialization yields a NULL pointer. Note that *no*
730 exception information is available even in this case -- the
731 exception information is held in the thread, and there is no
732 thread.
733
734 Locking: as above.
735
736*/
737
738PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000739Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyInterpreterState *interp;
742 PyThreadState *tstate, *save_tstate;
743 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (!initialized)
746 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 interp = PyInterpreterState_New();
749 if (interp == NULL)
750 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 tstate = PyThreadState_New(interp);
753 if (tstate == NULL) {
754 PyInterpreterState_Delete(interp);
755 return NULL;
756 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 interp->modules = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000763
Victor Stinner49d3f252010-10-17 01:24:53 +0000764 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 if (bimod != NULL) {
766 interp->builtins = PyModule_GetDict(bimod);
767 if (interp->builtins == NULL)
768 goto handle_error;
769 Py_INCREF(interp->builtins);
770 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 /* initialize builtin exceptions */
Brett Cannonfd074152012-04-14 14:10:13 -0400773 _PyExc_Init(bimod);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000774
Victor Stinner49d3f252010-10-17 01:24:53 +0000775 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 if (bimod != NULL && sysmod != NULL) {
777 PyObject *pstderr;
Brett Cannonfd074152012-04-14 14:10:13 -0400778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 interp->sysdict = PyModule_GetDict(sysmod);
780 if (interp->sysdict == NULL)
781 goto handle_error;
782 Py_INCREF(interp->sysdict);
783 PySys_SetPath(Py_GetPath());
784 PyDict_SetItemString(interp->sysdict, "modules",
785 interp->modules);
786 /* Set up a preliminary stderr printer until we have enough
787 infrastructure for the io module in place. */
788 pstderr = PyFile_NewStdPrinter(fileno(stderr));
789 if (pstderr == NULL)
790 Py_FatalError("Py_Initialize: can't set preliminary stderr");
Victor Stinnerbd303c12013-11-07 23:07:29 +0100791 _PySys_SetObjectId(&PyId_stderr, pstderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000793 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200796
Brett Cannonfd074152012-04-14 14:10:13 -0400797 import_init(interp, sysmod);
798
Victor Stinner793b5312011-04-27 00:24:21 +0200799 if (initfsencoding(interp) < 0)
800 goto handle_error;
801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 if (initstdio() < 0)
803 Py_FatalError(
804 "Py_Initialize: can't initialize sys standard streams");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000805 initmain(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 if (!Py_NoSiteFlag)
807 initsite();
808 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (!PyErr_Occurred())
811 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000812
Thomas Wouters89f507f2006-12-13 04:49:30 +0000813handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000815
Victor Stinnerc40a3502011-04-27 00:20:27 +0200816 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyThreadState_Clear(tstate);
818 PyThreadState_Swap(save_tstate);
819 PyThreadState_Delete(tstate);
820 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000823}
824
825/* Delete an interpreter and its last thread. This requires that the
826 given thread state is current, that the thread has no remaining
827 frames, and that it is its interpreter's only remaining thread.
828 It is a fatal error to violate these constraints.
829
830 (Py_Finalize() doesn't have these constraints -- it zaps
831 everything, regardless.)
832
833 Locking: as above.
834
835*/
836
837void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000838Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 if (tstate != PyThreadState_GET())
843 Py_FatalError("Py_EndInterpreter: thread is not current");
844 if (tstate->frame != NULL)
845 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Antoine Pitrou7eaf3f72013-08-25 19:48:18 +0200846
847 wait_for_thread_shutdown();
848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (tstate != interp->tstate_head || tstate->next != NULL)
850 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 PyImport_Cleanup();
853 PyInterpreterState_Clear(interp);
854 PyThreadState_Swap(NULL);
855 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000856}
857
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200858#ifdef MS_WINDOWS
Martin v. Löwis790465f2008-04-05 20:41:37 +0000859static wchar_t *progname = L"python";
Antoine Pitrou01cca5e2012-07-05 20:56:30 +0200860#else
861static wchar_t *progname = L"python3";
862#endif
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000863
864void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000865Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if (pn && *pn)
868 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000869}
870
Martin v. Löwis790465f2008-04-05 20:41:37 +0000871wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000872Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000875}
876
Martin v. Löwis790465f2008-04-05 20:41:37 +0000877static wchar_t *default_home = NULL;
Victor Stinner55a12202013-08-28 01:47:46 +0200878static wchar_t env_home[MAXPATHLEN+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000879
880void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000881Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000884}
885
Martin v. Löwis790465f2008-04-05 20:41:37 +0000886wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000887Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 wchar_t *home = default_home;
890 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
891 char* chome = Py_GETENV("PYTHONHOME");
892 if (chome) {
893 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
894 if (r != (size_t)-1 && r <= PATH_MAX)
895 home = env_home;
896 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 }
899 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000900}
901
Guido van Rossum6135a871995-01-09 17:53:26 +0000902/* Create __main__ module */
903
904static void
Nick Coghlan85e729e2012-07-15 18:09:52 +1000905initmain(PyInterpreterState *interp)
Guido van Rossum6135a871995-01-09 17:53:26 +0000906{
Brett Cannon13853a62013-05-04 17:37:09 -0400907 PyObject *m, *d, *loader;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 m = PyImport_AddModule("__main__");
909 if (m == NULL)
910 Py_FatalError("can't create __main__ module");
911 d = PyModule_GetDict(m);
912 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
913 PyObject *bimod = PyImport_ImportModule("builtins");
Nick Coghlan85e729e2012-07-15 18:09:52 +1000914 if (bimod == NULL) {
915 Py_FatalError("Failed to retrieve builtins module");
916 }
917 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
918 Py_FatalError("Failed to initialize __main__.__builtins__");
919 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 Py_DECREF(bimod);
921 }
Nick Coghlan85e729e2012-07-15 18:09:52 +1000922 /* Main is a little special - imp.is_builtin("__main__") will return
923 * False, but BuiltinImporter is still the most appropriate initial
924 * setting for its __loader__ attribute. A more suitable value will
925 * be set if __main__ gets further initialized later in the startup
926 * process.
927 */
Brett Cannon13853a62013-05-04 17:37:09 -0400928 loader = PyDict_GetItemString(d, "__loader__");
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400929 if (loader == NULL || loader == Py_None) {
Nick Coghlan85e729e2012-07-15 18:09:52 +1000930 PyObject *loader = PyObject_GetAttrString(interp->importlib,
931 "BuiltinImporter");
932 if (loader == NULL) {
933 Py_FatalError("Failed to retrieve BuiltinImporter");
934 }
935 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
936 Py_FatalError("Failed to initialize __main__.__loader__");
937 }
938 Py_DECREF(loader);
939 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000940}
941
Victor Stinner793b5312011-04-27 00:24:21 +0200942static int
943initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000944{
945 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000946
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200947 if (Py_FileSystemDefaultEncoding == NULL)
948 {
949 Py_FileSystemDefaultEncoding = get_locale_encoding();
950 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000951 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000952
Victor Stinnere4743092010-10-19 00:05:51 +0000953 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200954 interp->fscodec_initialized = 1;
955 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000956 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000957
958 /* the encoding is mbcs, utf-8 or ascii */
959 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
960 if (!codec) {
961 /* Such error can only occurs in critical situations: no more
962 * memory, import a module of the standard library failed,
963 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200964 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000965 }
Victor Stinner793b5312011-04-27 00:24:21 +0200966 Py_DECREF(codec);
967 interp->fscodec_initialized = 1;
968 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000969}
970
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000971/* Import the site module (not into __main__ though) */
972
973static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000974initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 PyObject *m;
977 m = PyImport_ImportModule("site");
978 if (m == NULL) {
Victor Stinner62ce62a2013-07-22 22:53:28 +0200979 fprintf(stderr, "Failed to import the site module\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyErr_Print();
981 Py_Finalize();
982 exit(1);
983 }
984 else {
985 Py_DECREF(m);
986 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000987}
988
Antoine Pitrou05608432009-01-09 18:53:14 +0000989static PyObject*
990create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 int fd, int write_mode, char* name,
992 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
995 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000996 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyObject *line_buffering;
998 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200999 _Py_IDENTIFIER(open);
1000 _Py_IDENTIFIER(isatty);
1001 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001002 _Py_IDENTIFIER(name);
1003 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 /* stdin is always opened in buffered mode, first because it shouldn't
1006 make a difference in common use cases, second because TextIOWrapper
1007 depends on the presence of a read1() method which only exists on
1008 buffered streams.
1009 */
1010 if (Py_UnbufferedStdioFlag && write_mode)
1011 buffering = 0;
1012 else
1013 buffering = -1;
1014 if (write_mode)
1015 mode = "wb";
1016 else
1017 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001018 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1019 fd, mode, buffering,
1020 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if (buf == NULL)
1022 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001025 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001026 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (raw == NULL)
1028 goto error;
1029 }
1030 else {
1031 raw = buf;
1032 Py_INCREF(raw);
1033 }
Antoine Pitrou05608432009-01-09 18:53:14 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001036 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001038 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 if (res == NULL)
1040 goto error;
1041 isatty = PyObject_IsTrue(res);
1042 Py_DECREF(res);
1043 if (isatty == -1)
1044 goto error;
1045 if (isatty || Py_UnbufferedStdioFlag)
1046 line_buffering = Py_True;
1047 else
1048 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 Py_CLEAR(raw);
1051 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +00001052
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001053#ifdef MS_WINDOWS
Victor Stinner7b3f0fa2012-08-04 01:28:00 +02001054 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1055 newlines to "\n".
1056 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1057 newline = NULL;
1058#else
1059 /* sys.stdin: split lines at "\n".
1060 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1061 newline = "\n";
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +00001062#endif
1063
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001064 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1065 buf, encoding, errors,
1066 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 Py_CLEAR(buf);
1068 if (stream == NULL)
1069 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (write_mode)
1072 mode = "w";
1073 else
1074 mode = "r";
1075 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001076 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 goto error;
1078 Py_CLEAR(text);
1079 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +00001080
1081error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 Py_XDECREF(buf);
1083 Py_XDECREF(stream);
1084 Py_XDECREF(text);
1085 Py_XDECREF(raw);
1086 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +00001087}
1088
Antoine Pitrou11942a52011-11-28 19:08:36 +01001089static int
1090is_valid_fd(int fd)
1091{
1092 int dummy_fd;
1093 if (fd < 0 || !_PyVerify_fd(fd))
1094 return 0;
1095 dummy_fd = dup(fd);
1096 if (dummy_fd < 0)
1097 return 0;
1098 close(dummy_fd);
1099 return 1;
1100}
1101
Georg Brandl1a3284e2007-12-02 09:40:06 +00001102/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001103static int
1104initstdio(void)
1105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 PyObject *iomod = NULL, *wrapper;
1107 PyObject *bimod = NULL;
1108 PyObject *m;
1109 PyObject *std = NULL;
1110 int status = 0, fd;
1111 PyObject * encoding_attr;
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001112 char *pythonioencoding = NULL, *encoding, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 /* Hack to avoid a nasty recursion issue when Python is invoked
1115 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1116 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1117 goto error;
1118 }
1119 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1122 goto error;
1123 }
1124 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (!(bimod = PyImport_ImportModule("builtins"))) {
1127 goto error;
1128 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 if (!(iomod = PyImport_ImportModule("io"))) {
1131 goto error;
1132 }
1133 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1134 goto error;
1135 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 /* Set builtins.open */
1138 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001139 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 goto error;
1141 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +00001142 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001143
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001144 encoding = _Py_StandardStreamEncoding;
1145 errors = _Py_StandardStreamErrors;
1146 if (!encoding || !errors) {
1147 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1148 if (pythonioencoding) {
1149 char *err;
1150 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1151 if (pythonioencoding == NULL) {
1152 PyErr_NoMemory();
1153 goto error;
1154 }
1155 err = strchr(pythonioencoding, ':');
1156 if (err) {
1157 *err = '\0';
1158 err++;
1159 if (*err && !errors) {
1160 errors = err;
1161 }
1162 }
1163 if (*pythonioencoding && !encoding) {
1164 encoding = pythonioencoding;
1165 }
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001166 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 }
Martin v. Löwis0f599892008-06-02 11:13:03 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 /* Set sys.stdin */
1170 fd = fileno(stdin);
1171 /* Under some conditions stdin, stdout and stderr may not be connected
1172 * and fileno() may point to an invalid file descriptor. For example
1173 * GUI apps don't have valid standard streams by default.
1174 */
Antoine Pitrou11942a52011-11-28 19:08:36 +01001175 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 std = Py_None;
1177 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 }
1179 else {
1180 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1181 if (std == NULL)
1182 goto error;
1183 } /* if (fd < 0) */
1184 PySys_SetObject("__stdin__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001185 _PySys_SetObjectId(&PyId_stdin, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 /* Set sys.stdout */
1189 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001190 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 std = Py_None;
1192 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 }
1194 else {
1195 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1196 if (std == NULL)
1197 goto error;
1198 } /* if (fd < 0) */
1199 PySys_SetObject("__stdout__", std);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001200 _PySys_SetObjectId(&PyId_stdout, std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001202
Guido van Rossum98297ee2007-11-06 21:34:58 +00001203#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /* Set sys.stderr, replaces the preliminary stderr */
1205 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001206 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 std = Py_None;
1208 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 }
1210 else {
1211 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1212 if (std == NULL)
1213 goto error;
1214 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 /* Same as hack above, pre-import stderr's codec to avoid recursion
1217 when import.c tries to write to stderr in verbose mode. */
1218 encoding_attr = PyObject_GetAttrString(std, "encoding");
1219 if (encoding_attr != NULL) {
Victor Stinner49fc8ec2013-07-07 23:30:24 +02001220 const char * std_encoding;
1221 std_encoding = _PyUnicode_AsString(encoding_attr);
1222 if (std_encoding != NULL) {
1223 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001224 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001226 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 }
1228 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001229
Victor Stinnerba308832013-07-22 23:55:19 +02001230 if (PySys_SetObject("__stderr__", std) < 0) {
1231 Py_DECREF(std);
1232 goto error;
1233 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01001234 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
Victor Stinnerba308832013-07-22 23:55:19 +02001235 Py_DECREF(std);
1236 goto error;
1237 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001239#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001242 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 status = -1;
1244 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001245
Nick Coghlan7d270ee2013-10-17 22:35:35 +10001246 /* We won't need them anymore. */
1247 if (_Py_StandardStreamEncoding) {
1248 PyMem_RawFree(_Py_StandardStreamEncoding);
1249 _Py_StandardStreamEncoding = NULL;
1250 }
1251 if (_Py_StandardStreamErrors) {
1252 PyMem_RawFree(_Py_StandardStreamErrors);
1253 _Py_StandardStreamErrors = NULL;
1254 }
Serhiy Storchakabf28d2d2013-09-13 11:46:24 +03001255 PyMem_Free(pythonioencoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 Py_XDECREF(bimod);
1257 Py_XDECREF(iomod);
1258 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001259}
1260
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001261/* Parse input from a file and execute it */
1262
1263int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001264PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 if (filename == NULL)
1268 filename = "???";
1269 if (Py_FdIsInteractive(fp, filename)) {
1270 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1271 if (closeit)
1272 fclose(fp);
1273 return err;
1274 }
1275 else
1276 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001277}
1278
1279int
Victor Stinner95701bd2013-11-06 18:41:07 +01001280PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001281{
Victor Stinner95701bd2013-11-06 18:41:07 +01001282 PyObject *filename, *v;
1283 int ret, err;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001285
Victor Stinner95701bd2013-11-06 18:41:07 +01001286 filename = PyUnicode_DecodeFSDefault(filename_str);
1287 if (filename == NULL) {
1288 PyErr_Print();
1289 return -1;
1290 }
1291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (flags == NULL) {
1293 flags = &local_flags;
1294 local_flags.cf_flags = 0;
1295 }
Victor Stinner09054372013-11-06 22:41:44 +01001296 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001298 _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>> "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 Py_XDECREF(v);
1300 }
Victor Stinner09054372013-11-06 22:41:44 +01001301 v = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (v == NULL) {
Victor Stinner09054372013-11-06 22:41:44 +01001303 _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 Py_XDECREF(v);
1305 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001306 err = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 for (;;) {
Victor Stinner95701bd2013-11-06 18:41:07 +01001308 ret = PyRun_InteractiveOneObject(fp, filename, flags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 PRINT_TOTAL_REFS();
Victor Stinner95701bd2013-11-06 18:41:07 +01001310 if (ret == E_EOF) {
1311 err = 0;
1312 break;
1313 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 /*
1315 if (ret == E_NOMEM)
Victor Stinner95701bd2013-11-06 18:41:07 +01001316 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 */
1318 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001319 Py_DECREF(filename);
1320 return err;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001321}
1322
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001323/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001324static int PARSER_FLAGS(PyCompilerFlags *flags)
1325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 int parser_flags = 0;
1327 if (!flags)
1328 return 0;
1329 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1330 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1331 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1332 parser_flags |= PyPARSE_IGNORE_COOKIE;
1333 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1334 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1335 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001336}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001337
Thomas Wouters89f507f2006-12-13 04:49:30 +00001338#if 0
1339/* Keep an example of flags with future keyword support. */
1340#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1342 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1343 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1344 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001345#endif
1346
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001347int
Victor Stinner95701bd2013-11-06 18:41:07 +01001348PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001349{
Victor Stinner95701bd2013-11-06 18:41:07 +01001350 PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 mod_ty mod;
1352 PyArena *arena;
1353 char *ps1 = "", *ps2 = "", *enc = NULL;
1354 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001355 _Py_IDENTIFIER(encoding);
Victor Stinner95701bd2013-11-06 18:41:07 +01001356 _Py_IDENTIFIER(__main__);
1357
1358 mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
1359 if (mod_name == NULL) {
1360 PyErr_Print();
1361 return -1;
1362 }
Tim Petersfe2127d2001-07-16 05:37:24 +00001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 if (fp == stdin) {
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001365 /* Fetch encoding from sys.stdin if possible. */
Victor Stinnerbd303c12013-11-07 23:07:29 +01001366 v = _PySys_GetObjectId(&PyId_stdin);
Benjamin Petersonfe1b22a2013-04-29 10:23:08 -04001367 if (v && v != Py_None) {
1368 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
1369 if (oenc)
1370 enc = _PyUnicode_AsString(oenc);
1371 if (!enc)
1372 PyErr_Clear();
1373 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 }
Victor Stinner09054372013-11-06 22:41:44 +01001375 v = _PySys_GetObjectId(&PyId_ps1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 if (v != NULL) {
1377 v = PyObject_Str(v);
1378 if (v == NULL)
1379 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001380 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001382 if (ps1 == NULL) {
1383 PyErr_Clear();
1384 ps1 = "";
1385 }
1386 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 }
Victor Stinner09054372013-11-06 22:41:44 +01001388 w = _PySys_GetObjectId(&PyId_ps2);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 if (w != NULL) {
1390 w = PyObject_Str(w);
1391 if (w == NULL)
1392 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001393 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001395 if (ps2 == NULL) {
1396 PyErr_Clear();
1397 ps2 = "";
1398 }
1399 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 }
1401 arena = PyArena_New();
1402 if (arena == NULL) {
1403 Py_XDECREF(v);
1404 Py_XDECREF(w);
1405 Py_XDECREF(oenc);
1406 return -1;
1407 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001408 mod = PyParser_ASTFromFileObject(fp, filename, enc,
1409 Py_single_input, ps1, ps2,
1410 flags, &errcode, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 Py_XDECREF(v);
1412 Py_XDECREF(w);
1413 Py_XDECREF(oenc);
1414 if (mod == NULL) {
1415 PyArena_Free(arena);
1416 if (errcode == E_EOF) {
1417 PyErr_Clear();
1418 return E_EOF;
1419 }
1420 PyErr_Print();
1421 return -1;
1422 }
Victor Stinner95701bd2013-11-06 18:41:07 +01001423 m = PyImport_AddModuleObject(mod_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 if (m == NULL) {
1425 PyArena_Free(arena);
1426 return -1;
1427 }
1428 d = PyModule_GetDict(m);
1429 v = run_mod(mod, filename, d, d, flags, arena);
1430 PyArena_Free(arena);
1431 flush_io();
1432 if (v == NULL) {
1433 PyErr_Print();
1434 return -1;
1435 }
1436 Py_DECREF(v);
1437 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001438}
1439
Victor Stinner95701bd2013-11-06 18:41:07 +01001440int
1441PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
1442{
1443 PyObject *filename;
1444 int res;
1445
1446 filename = PyUnicode_DecodeFSDefault(filename_str);
1447 if (filename == NULL) {
1448 PyErr_Print();
1449 return -1;
1450 }
1451 res = PyRun_InteractiveOneObject(fp, filename, flags);
1452 Py_DECREF(filename);
1453 return res;
1454}
1455
1456
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001457/* Check whether a file maybe a pyc file: Look at the extension,
1458 the file type, and, if we may close it, at the first few bytes. */
1459
1460static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001461maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1464 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 /* Only look into the file if we are allowed to close it, since
1467 it then should also be seekable. */
1468 if (closeit) {
1469 /* Read only two bytes of the magic. If the file was opened in
1470 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1471 be read as they are on disk. */
1472 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1473 unsigned char buf[2];
1474 /* Mess: In case of -x, the stream is NOT at its start now,
1475 and ungetc() was used to push back the first newline,
1476 which makes the current stream position formally undefined,
1477 and a x-platform nightmare.
1478 Unfortunately, we have no direct way to know whether -x
1479 was specified. So we use a terrible hack: if the current
1480 stream position is not 0, we assume -x was specified, and
1481 give up. Bug 132850 on SourceForge spells out the
1482 hopelessness of trying anything else (fseek and ftell
1483 don't work predictably x-platform for text-mode files).
1484 */
1485 int ispyc = 0;
1486 if (ftell(fp) == 0) {
1487 if (fread(buf, 1, 2, fp) == 2 &&
1488 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1489 ispyc = 1;
1490 rewind(fp);
1491 }
1492 return ispyc;
1493 }
1494 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001495}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001496
Antoine Pitrou32d483c2013-07-30 21:01:23 +02001497static int
1498set_main_loader(PyObject *d, const char *filename, const char *loader_name)
Nick Coghlan85e729e2012-07-15 18:09:52 +10001499{
1500 PyInterpreterState *interp;
1501 PyThreadState *tstate;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001502 PyObject *filename_obj, *loader_type, *loader;
Nick Coghlanb7a58942012-07-15 23:21:08 +10001503 int result = 0;
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001504
1505 filename_obj = PyUnicode_DecodeFSDefault(filename);
1506 if (filename_obj == NULL)
1507 return -1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001508 /* Get current thread state and interpreter pointer */
1509 tstate = PyThreadState_GET();
1510 interp = tstate->interp;
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001511 loader_type = PyObject_GetAttrString(interp->importlib, loader_name);
1512 if (loader_type == NULL) {
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001513 Py_DECREF(filename_obj);
Nick Coghlan3f94cbf2012-07-15 19:10:39 +10001514 return -1;
1515 }
Andrew Svetlov90c0eb22012-11-01 14:51:14 +02001516 loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001517 Py_DECREF(loader_type);
1518 if (loader == NULL) {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001519 return -1;
1520 }
Nick Coghlanb7a58942012-07-15 23:21:08 +10001521 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1522 result = -1;
1523 }
Nick Coghlan85e729e2012-07-15 18:09:52 +10001524 Py_DECREF(loader);
Nick Coghlanb7a58942012-07-15 23:21:08 +10001525 return result;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001526}
1527
1528int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001529PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 PyObject *m, *d, *v;
1533 const char *ext;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001534 int set_file_name = 0, ret = -1;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001535 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 m = PyImport_AddModule("__main__");
1538 if (m == NULL)
1539 return -1;
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001540 Py_INCREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 d = PyModule_GetDict(m);
1542 if (PyDict_GetItemString(d, "__file__") == NULL) {
1543 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001544 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (f == NULL)
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001546 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1548 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001549 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001551 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1552 Py_DECREF(f);
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001553 goto done;
Barry Warsaw916048d2011-09-20 14:45:44 -04001554 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 set_file_name = 1;
1556 Py_DECREF(f);
1557 }
1558 len = strlen(filename);
1559 ext = filename + len - (len > 4 ? 4 : 0);
1560 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Christian Heimes04ac4c12012-09-11 15:47:28 +02001561 FILE *pyc_fp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 /* Try to run a pyc file. First, re-open in binary */
1563 if (closeit)
1564 fclose(fp);
Victor Stinnerdaf45552013-08-28 00:53:59 +02001565 if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 fprintf(stderr, "python: Can't reopen .pyc file\n");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 goto done;
1568 }
1569 /* Turn on optimization if a .pyo file is given */
1570 if (strcmp(ext, ".pyo") == 0)
1571 Py_OptimizeFlag = 1;
Nick Coghlan85e729e2012-07-15 18:09:52 +10001572
1573 if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) {
1574 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1575 ret = -1;
Christian Heimes04ac4c12012-09-11 15:47:28 +02001576 fclose(pyc_fp);
Nick Coghlan85e729e2012-07-15 18:09:52 +10001577 goto done;
1578 }
Christian Heimes04ac4c12012-09-11 15:47:28 +02001579 v = run_pyc_file(pyc_fp, filename, d, d, flags);
1580 fclose(pyc_fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 } else {
Nick Coghlan85e729e2012-07-15 18:09:52 +10001582 /* When running from stdin, leave __main__.__loader__ alone */
1583 if (strcmp(filename, "<stdin>") != 0 &&
1584 set_main_loader(d, filename, "SourceFileLoader") < 0) {
1585 fprintf(stderr, "python: failed to set __main__.__loader__\n");
1586 ret = -1;
1587 goto done;
1588 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1590 closeit, flags);
1591 }
1592 flush_io();
1593 if (v == NULL) {
1594 PyErr_Print();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 goto done;
1596 }
1597 Py_DECREF(v);
1598 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001599 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1601 PyErr_Clear();
Hynek Schlawack5c6b3e22012-11-07 09:02:24 +01001602 Py_DECREF(m);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001604}
1605
1606int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001607PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 PyObject *m, *d, *v;
1610 m = PyImport_AddModule("__main__");
1611 if (m == NULL)
1612 return -1;
1613 d = PyModule_GetDict(m);
1614 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1615 if (v == NULL) {
1616 PyErr_Print();
1617 return -1;
1618 }
1619 Py_DECREF(v);
1620 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001621}
1622
Barry Warsaw035574d1997-08-29 22:07:17 +00001623static int
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001624parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename,
1625 int *lineno, int *offset, PyObject **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 long hold;
1628 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001629 _Py_IDENTIFIER(msg);
1630 _Py_IDENTIFIER(filename);
1631 _Py_IDENTIFIER(lineno);
1632 _Py_IDENTIFIER(offset);
1633 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001634
Benjamin Peterson80d50422012-04-03 00:30:38 -04001635 *message = NULL;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001636 *filename = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 /* new style errors. `err' is an instance */
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001639 *message = _PyObject_GetAttrId(err, &PyId_msg);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001640 if (!*message)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001642
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001643 v = _PyObject_GetAttrId(err, &PyId_filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001644 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001645 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001646 if (v == Py_None) {
1647 Py_DECREF(v);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001648 *filename = _PyUnicode_FromId(&PyId_string);
1649 if (*filename == NULL)
1650 goto finally;
1651 Py_INCREF(*filename);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001652 }
1653 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001654 *filename = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001655 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001656
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001657 v = _PyObject_GetAttrId(err, &PyId_lineno);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001658 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 goto finally;
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 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001665
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001666 v = _PyObject_GetAttrId(err, &PyId_offset);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001667 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 goto finally;
1669 if (v == Py_None) {
1670 *offset = -1;
1671 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 } else {
1673 hold = PyLong_AsLong(v);
1674 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (hold < 0 && PyErr_Occurred())
1676 goto finally;
1677 *offset = (int)hold;
1678 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001679
Benjamin Peterson0a9a6362012-04-03 00:35:36 -04001680 v = _PyObject_GetAttrId(err, &PyId_text);
Benjamin Peterson80d50422012-04-03 00:30:38 -04001681 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 goto finally;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001683 if (v == Py_None) {
1684 Py_DECREF(v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 *text = NULL;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001686 }
1687 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001688 *text = v;
Benjamin Peterson80d50422012-04-03 00:30:38 -04001689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001691
1692finally:
Benjamin Peterson80d50422012-04-03 00:30:38 -04001693 Py_XDECREF(*message);
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001694 Py_XDECREF(*filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001696}
1697
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001698void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001699PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001702}
1703
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001704static void
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001705print_error_text(PyObject *f, int offset, PyObject *text_obj)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001706{
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001707 char *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 char *nl;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001709
1710 text = _PyUnicode_AsString(text_obj);
1711 if (text == NULL)
1712 return;
1713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001715 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1716 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 for (;;) {
1718 nl = strchr(text, '\n');
1719 if (nl == NULL || nl-text >= offset)
1720 break;
1721 offset -= (int)(nl+1-text);
1722 text = nl+1;
1723 }
1724 while (*text == ' ' || *text == '\t') {
1725 text++;
1726 offset--;
1727 }
1728 }
1729 PyFile_WriteString(" ", f);
1730 PyFile_WriteString(text, f);
1731 if (*text == '\0' || text[strlen(text)-1] != '\n')
1732 PyFile_WriteString("\n", f);
1733 if (offset == -1)
1734 return;
1735 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001736 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001739}
1740
Guido van Rossum66e8e862001-03-23 17:54:43 +00001741static void
1742handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 PyObject *exception, *value, *tb;
1745 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 if (Py_InspectFlag)
1748 /* Don't exit if -i flag was given. This flag is set to 0
1749 * when entering interactive mode for inspecting. */
1750 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 PyErr_Fetch(&exception, &value, &tb);
1753 fflush(stdout);
1754 if (value == NULL || value == Py_None)
1755 goto done;
1756 if (PyExceptionInstance_Check(value)) {
1757 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001758 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001759 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 if (code) {
1761 Py_DECREF(value);
1762 value = code;
1763 if (value == Py_None)
1764 goto done;
1765 }
1766 /* If we failed to dig out the 'code' attribute,
1767 just let the else clause below print the error. */
1768 }
1769 if (PyLong_Check(value))
1770 exitcode = (int)PyLong_AsLong(value);
1771 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001772 PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
Victor Stinner7126dbc2010-05-21 23:45:42 +00001773 if (sys_stderr != NULL && sys_stderr != Py_None) {
1774 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1775 } else {
1776 PyObject_Print(value, stderr, Py_PRINT_RAW);
1777 fflush(stderr);
1778 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PySys_WriteStderr("\n");
1780 exitcode = 1;
1781 }
Tim Peterscf615b52003-04-19 18:47:02 +00001782 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 /* Restore and clear the exception info, in order to properly decref
1784 * the exception, value, and traceback. If we just exit instead,
1785 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1786 * some finalizers from running.
1787 */
1788 PyErr_Restore(exception, value, tb);
1789 PyErr_Clear();
1790 Py_Exit(exitcode);
1791 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001792}
1793
1794void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001795PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1800 handle_system_exit();
1801 }
1802 PyErr_Fetch(&exception, &v, &tb);
1803 if (exception == NULL)
1804 return;
1805 PyErr_NormalizeException(&exception, &v, &tb);
1806 if (tb == NULL) {
1807 tb = Py_None;
1808 Py_INCREF(tb);
1809 }
1810 PyException_SetTraceback(v, tb);
1811 if (exception == NULL)
1812 return;
1813 /* Now we know v != NULL too */
1814 if (set_sys_last_vars) {
Victor Stinner09054372013-11-06 22:41:44 +01001815 _PySys_SetObjectId(&PyId_last_type, exception);
1816 _PySys_SetObjectId(&PyId_last_value, v);
1817 _PySys_SetObjectId(&PyId_last_traceback, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 }
Victor Stinner09054372013-11-06 22:41:44 +01001819 hook = _PySys_GetObjectId(&PyId_excepthook);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 if (hook) {
1821 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1822 PyObject *result = PyEval_CallObject(hook, args);
1823 if (result == NULL) {
1824 PyObject *exception2, *v2, *tb2;
1825 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1826 handle_system_exit();
1827 }
1828 PyErr_Fetch(&exception2, &v2, &tb2);
1829 PyErr_NormalizeException(&exception2, &v2, &tb2);
1830 /* It should not be possible for exception2 or v2
1831 to be NULL. However PyErr_Display() can't
1832 tolerate NULLs, so just be safe. */
1833 if (exception2 == NULL) {
1834 exception2 = Py_None;
1835 Py_INCREF(exception2);
1836 }
1837 if (v2 == NULL) {
1838 v2 = Py_None;
1839 Py_INCREF(v2);
1840 }
1841 fflush(stdout);
1842 PySys_WriteStderr("Error in sys.excepthook:\n");
1843 PyErr_Display(exception2, v2, tb2);
1844 PySys_WriteStderr("\nOriginal exception was:\n");
1845 PyErr_Display(exception, v, tb);
1846 Py_DECREF(exception2);
1847 Py_DECREF(v2);
1848 Py_XDECREF(tb2);
1849 }
1850 Py_XDECREF(result);
1851 Py_XDECREF(args);
1852 } else {
1853 PySys_WriteStderr("sys.excepthook is missing\n");
1854 PyErr_Display(exception, v, tb);
1855 }
1856 Py_XDECREF(exception);
1857 Py_XDECREF(v);
1858 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001859}
1860
Benjamin Petersone6528212008-07-15 15:32:09 +00001861static void
1862print_exception(PyObject *f, PyObject *value)
1863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001864 int err = 0;
1865 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001866 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 if (!PyExceptionInstance_Check(value)) {
1869 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1870 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1871 PyFile_WriteString(" found\n", f);
1872 return;
1873 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 Py_INCREF(value);
1876 fflush(stdout);
1877 type = (PyObject *) Py_TYPE(value);
1878 tb = PyException_GetTraceback(value);
1879 if (tb && tb != Py_None)
1880 err = PyTraceBack_Print(tb, f);
1881 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001882 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001884 PyObject *message, *filename, *text;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 int lineno, offset;
1886 if (!parse_syntax_error(value, &message, &filename,
1887 &lineno, &offset, &text))
1888 PyErr_Clear();
1889 else {
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001890 PyObject *line;
1891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001892 Py_DECREF(value);
1893 value = message;
Victor Stinnerefa7a0e2013-11-07 12:37:56 +01001894
1895 line = PyUnicode_FromFormat(" File \"%U\", line %d\n",
1896 filename, lineno);
1897 Py_DECREF(filename);
1898 if (line != NULL) {
1899 PyFile_WriteObject(line, f, Py_PRINT_RAW);
1900 Py_DECREF(line);
1901 }
1902
1903 if (text != NULL) {
1904 print_error_text(f, offset, text);
1905 Py_DECREF(text);
1906 }
1907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 /* Can't be bothered to check all those
1909 PyFile_WriteString() calls */
1910 if (PyErr_Occurred())
1911 err = -1;
1912 }
1913 }
1914 if (err) {
1915 /* Don't do anything else */
1916 }
1917 else {
1918 PyObject* moduleName;
1919 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001920 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 assert(PyExceptionClass_Check(type));
1922 className = PyExceptionClass_Name(type);
1923 if (className != NULL) {
1924 char *dot = strrchr(className, '.');
1925 if (dot != NULL)
1926 className = dot+1;
1927 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001928
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001929 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1931 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001932 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 err = PyFile_WriteString("<unknown>", f);
1934 }
1935 else {
Victor Stinnerbd303c12013-11-07 23:07:29 +01001936 if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 {
Victor Stinner937114f2013-11-07 00:12:30 +01001938 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 err += PyFile_WriteString(".", f);
1940 }
1941 Py_DECREF(moduleName);
1942 }
1943 if (err == 0) {
1944 if (className == NULL)
1945 err = PyFile_WriteString("<unknown>", f);
1946 else
1947 err = PyFile_WriteString(className, f);
1948 }
1949 }
1950 if (err == 0 && (value != Py_None)) {
1951 PyObject *s = PyObject_Str(value);
1952 /* only print colon if the str() of the
1953 object is not the empty string
1954 */
1955 if (s == NULL)
1956 err = -1;
1957 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001958 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 err = PyFile_WriteString(": ", f);
1960 if (err == 0)
1961 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1962 Py_XDECREF(s);
1963 }
1964 /* try to write a newline in any case */
1965 err += PyFile_WriteString("\n", f);
1966 Py_XDECREF(tb);
1967 Py_DECREF(value);
1968 /* If an error happened here, don't show it.
1969 XXX This is wrong, but too many callers rely on this behavior. */
1970 if (err != 0)
1971 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001972}
1973
1974static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 "\nThe above exception was the direct cause "
1976 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001977
1978static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 "\nDuring handling of the above exception, "
1980 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001981
1982static void
1983print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 int err = 0, res;
1986 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 if (seen != NULL) {
1989 /* Exception chaining */
1990 if (PySet_Add(seen, value) == -1)
1991 PyErr_Clear();
1992 else if (PyExceptionInstance_Check(value)) {
1993 cause = PyException_GetCause(value);
1994 context = PyException_GetContext(value);
Benjamin Petersond5a1c442012-05-14 22:09:31 -07001995 if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 res = PySet_Contains(seen, cause);
1997 if (res == -1)
1998 PyErr_Clear();
1999 if (res == 0) {
2000 print_exception_recursive(
2001 f, cause, seen);
2002 err |= PyFile_WriteString(
2003 cause_message, f);
2004 }
2005 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -07002006 else if (context &&
2007 !((PyBaseExceptionObject *)value)->suppress_context) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 res = PySet_Contains(seen, context);
2009 if (res == -1)
2010 PyErr_Clear();
2011 if (res == 0) {
2012 print_exception_recursive(
2013 f, context, seen);
2014 err |= PyFile_WriteString(
2015 context_message, f);
2016 }
2017 }
2018 Py_XDECREF(context);
2019 Py_XDECREF(cause);
2020 }
2021 }
2022 print_exception(f, value);
2023 if (err != 0)
2024 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00002025}
2026
Thomas Wouters477c8d52006-05-27 19:21:47 +00002027void
2028PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002029{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 PyObject *seen;
Victor Stinnerbd303c12013-11-07 23:07:29 +01002031 PyObject *f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrou24201d42013-10-13 21:53:13 +02002032 if (PyExceptionInstance_Check(value)
2033 && tb != NULL && PyTraceBack_Check(tb)) {
2034 /* Put the traceback on the exception, otherwise it won't get
2035 displayed. See issue #18776. */
2036 PyObject *cur_tb = PyException_GetTraceback(value);
2037 if (cur_tb == NULL)
2038 PyException_SetTraceback(value, tb);
2039 else
2040 Py_DECREF(cur_tb);
2041 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 if (f == Py_None) {
2043 /* pass */
2044 }
2045 else if (f == NULL) {
2046 _PyObject_Dump(value);
2047 fprintf(stderr, "lost sys.stderr\n");
2048 }
2049 else {
2050 /* We choose to ignore seen being possibly NULL, and report
2051 at least the main exception (it could be a MemoryError).
2052 */
2053 seen = PySet_New(NULL);
2054 if (seen == NULL)
2055 PyErr_Clear();
2056 print_exception_recursive(f, value, seen);
2057 Py_XDECREF(seen);
2058 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002059}
2060
Guido van Rossum82598051997-03-05 00:20:32 +00002061PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002062PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 PyObject *ret = NULL;
2066 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002067 PyArena *arena;
Victor Stinner95701bd2013-11-06 18:41:07 +01002068 PyObject *filename;
2069
2070 filename = _PyUnicode_FromId(&PyId_string); /* borrowed */
2071 if (filename == NULL)
2072 return NULL;
2073
2074 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 if (arena == NULL)
2076 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002077
Victor Stinner95701bd2013-11-06 18:41:07 +01002078 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 if (mod != NULL)
Victor Stinner95701bd2013-11-06 18:41:07 +01002080 ret = run_mod(mod, filename, globals, locals, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 PyArena_Free(arena);
2082 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002083}
2084
2085PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002086PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002088{
Victor Stinner95701bd2013-11-06 18:41:07 +01002089 PyObject *ret = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 mod_ty mod;
Victor Stinner95701bd2013-11-06 18:41:07 +01002091 PyArena *arena = NULL;
2092 PyObject *filename;
Guido van Rossum98297ee2007-11-06 21:34:58 +00002093
Victor Stinner95701bd2013-11-06 18:41:07 +01002094 filename = PyUnicode_DecodeFSDefault(filename_str);
2095 if (filename == NULL)
2096 goto exit;
2097
2098 arena = PyArena_New();
2099 if (arena == NULL)
2100 goto exit;
2101
2102 mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0,
2103 flags, NULL, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (closeit)
2105 fclose(fp);
2106 if (mod == NULL) {
Victor Stinner95701bd2013-11-06 18:41:07 +01002107 goto exit;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 }
2109 ret = run_mod(mod, filename, globals, locals, flags, arena);
Victor Stinner95701bd2013-11-06 18:41:07 +01002110
2111exit:
2112 Py_XDECREF(filename);
2113 if (arena != NULL)
2114 PyArena_Free(arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002116}
2117
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002118static void
2119flush_io(void)
2120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 PyObject *f, *r;
2122 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002123 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 /* Save the current exception */
2126 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002127
Victor Stinnerbd303c12013-11-07 23:07:29 +01002128 f = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002130 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 if (r)
2132 Py_DECREF(r);
2133 else
2134 PyErr_Clear();
2135 }
Victor Stinnerbd303c12013-11-07 23:07:29 +01002136 f = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002138 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (r)
2140 Py_DECREF(r);
2141 else
2142 PyErr_Clear();
2143 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00002146}
2147
Guido van Rossum82598051997-03-05 00:20:32 +00002148static PyObject *
Victor Stinner95701bd2013-11-06 18:41:07 +01002149run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals,
2150 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyCodeObject *co;
2153 PyObject *v;
Victor Stinner95701bd2013-11-06 18:41:07 +01002154 co = PyAST_CompileObject(mod, filename, flags, -1, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 if (co == NULL)
2156 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002157 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 Py_DECREF(co);
2159 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002160}
2161
Guido van Rossum82598051997-03-05 00:20:32 +00002162static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002163run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00002165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 PyCodeObject *co;
2167 PyObject *v;
2168 long magic;
2169 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 magic = PyMarshal_ReadLongFromFile(fp);
2172 if (magic != PyImport_GetMagicNumber()) {
2173 PyErr_SetString(PyExc_RuntimeError,
2174 "Bad magic number in .pyc file");
2175 return NULL;
2176 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01002177 /* Skip mtime and size */
2178 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002179 (void) PyMarshal_ReadLongFromFile(fp);
2180 v = PyMarshal_ReadLastObjectFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 if (v == NULL || !PyCode_Check(v)) {
2182 Py_XDECREF(v);
2183 PyErr_SetString(PyExc_RuntimeError,
2184 "Bad code object in .pyc file");
2185 return NULL;
2186 }
2187 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002188 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 if (v && flags)
2190 flags->cf_flags |= (co->co_flags & PyCF_MASK);
2191 Py_DECREF(co);
2192 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00002193}
2194
Guido van Rossum82598051997-03-05 00:20:32 +00002195PyObject *
Victor Stinner14e461d2013-08-26 22:28:21 +02002196Py_CompileStringObject(const char *str, PyObject *filename, int start,
2197 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00002198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 PyCodeObject *co;
2200 mod_ty mod;
2201 PyArena *arena = PyArena_New();
2202 if (arena == NULL)
2203 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002204
Victor Stinner14e461d2013-08-26 22:28:21 +02002205 mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 if (mod == NULL) {
2207 PyArena_Free(arena);
2208 return NULL;
2209 }
2210 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
2211 PyObject *result = PyAST_mod2obj(mod);
2212 PyArena_Free(arena);
2213 return result;
2214 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002215 co = PyAST_CompileObject(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 PyArena_Free(arena);
2217 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00002218}
2219
Victor Stinner14e461d2013-08-26 22:28:21 +02002220PyObject *
2221Py_CompileStringExFlags(const char *str, const char *filename_str, int start,
2222 PyCompilerFlags *flags, int optimize)
2223{
2224 PyObject *filename, *co;
2225 filename = PyUnicode_DecodeFSDefault(filename_str);
2226 if (filename == NULL)
2227 return NULL;
2228 co = Py_CompileStringObject(str, filename, start, flags, optimize);
2229 Py_DECREF(filename);
2230 return co;
2231}
2232
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002233/* For use in Py_LIMITED_API */
2234#undef Py_CompileString
2235PyObject *
2236PyCompileString(const char *str, const char *filename, int start)
2237{
2238 return Py_CompileStringFlags(str, filename, start, NULL);
2239}
2240
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002241struct symtable *
Victor Stinner14e461d2013-08-26 22:28:21 +02002242Py_SymtableStringObject(const char *str, PyObject *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 struct symtable *st;
2245 mod_ty mod;
2246 PyCompilerFlags flags;
Victor Stinner14e461d2013-08-26 22:28:21 +02002247 PyArena *arena;
2248
2249 arena = PyArena_New();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 if (arena == NULL)
2251 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 flags.cf_flags = 0;
Victor Stinner14e461d2013-08-26 22:28:21 +02002254 mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 if (mod == NULL) {
2256 PyArena_Free(arena);
2257 return NULL;
2258 }
Victor Stinner14e461d2013-08-26 22:28:21 +02002259 st = PySymtable_BuildObject(mod, filename, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 PyArena_Free(arena);
2261 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00002262}
2263
Victor Stinner14e461d2013-08-26 22:28:21 +02002264struct symtable *
2265Py_SymtableString(const char *str, const char *filename_str, int start)
2266{
2267 PyObject *filename;
2268 struct symtable *st;
2269
2270 filename = PyUnicode_DecodeFSDefault(filename_str);
2271 if (filename == NULL)
2272 return NULL;
2273 st = Py_SymtableStringObject(str, filename, start);
2274 Py_DECREF(filename);
2275 return st;
2276}
2277
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002278/* Preferred access to parser is through AST. */
2279mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002280PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start,
2281 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 mod_ty mod;
2284 PyCompilerFlags localflags;
2285 perrdetail err;
2286 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002287
Victor Stinner14e461d2013-08-26 22:28:21 +02002288 node *n = PyParser_ParseStringObject(s, filename,
2289 &_PyParser_Grammar, start, &err,
2290 &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 if (flags == NULL) {
2292 localflags.cf_flags = 0;
2293 flags = &localflags;
2294 }
2295 if (n) {
2296 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002297 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002299 }
2300 else {
2301 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002302 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002304 err_free(&err);
2305 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002306}
2307
2308mod_ty
Victor Stinner14e461d2013-08-26 22:28:21 +02002309PyParser_ASTFromString(const char *s, const char *filename_str, int start,
2310 PyCompilerFlags *flags, PyArena *arena)
2311{
2312 PyObject *filename;
2313 mod_ty mod;
2314 filename = PyUnicode_DecodeFSDefault(filename_str);
2315 if (filename == NULL)
2316 return NULL;
2317 mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena);
2318 Py_DECREF(filename);
2319 return mod;
2320}
2321
2322mod_ty
2323PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc,
2324 int start, char *ps1,
2325 char *ps2, PyCompilerFlags *flags, int *errcode,
2326 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 mod_ty mod;
2329 PyCompilerFlags localflags;
2330 perrdetail err;
2331 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00002332
Victor Stinner14e461d2013-08-26 22:28:21 +02002333 node *n = PyParser_ParseFileObject(fp, filename, enc,
2334 &_PyParser_Grammar,
2335 start, ps1, ps2, &err, &iflags);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 if (flags == NULL) {
2337 localflags.cf_flags = 0;
2338 flags = &localflags;
2339 }
2340 if (n) {
2341 flags->cf_flags |= iflags & PyCF_MASK;
Victor Stinner14e461d2013-08-26 22:28:21 +02002342 mod = PyAST_FromNodeObject(n, flags, filename, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 }
2345 else {
2346 err_input(&err);
2347 if (errcode)
2348 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02002349 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002351 err_free(&err);
2352 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002353}
2354
Victor Stinner14e461d2013-08-26 22:28:21 +02002355mod_ty
2356PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc,
2357 int start, char *ps1,
2358 char *ps2, PyCompilerFlags *flags, int *errcode,
2359 PyArena *arena)
2360{
2361 mod_ty mod;
2362 PyObject *filename;
2363 filename = PyUnicode_DecodeFSDefault(filename_str);
2364 if (filename == NULL)
2365 return NULL;
2366 mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2,
2367 flags, errcode, arena);
2368 Py_DECREF(filename);
2369 return mod;
2370}
2371
Guido van Rossuma110aa61994-08-29 12:50:44 +00002372/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002373
Guido van Rossuma110aa61994-08-29 12:50:44 +00002374node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002375PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 perrdetail err;
2378 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2379 &_PyParser_Grammar,
2380 start, NULL, NULL, &err, flags);
2381 if (n == NULL)
2382 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002383 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002386}
2387
Guido van Rossuma110aa61994-08-29 12:50:44 +00002388/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002389
Guido van Rossuma110aa61994-08-29 12:50:44 +00002390node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002391PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 perrdetail err;
2394 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2395 start, &err, flags);
2396 if (n == NULL)
2397 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002398 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002400}
2401
2402node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002403PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 perrdetail err;
2407 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2408 &_PyParser_Grammar, start, &err, flags);
2409 if (n == NULL)
2410 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002411 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002413}
2414
2415node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002416PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002419}
2420
Guido van Rossum66ebd912003-04-17 16:02:26 +00002421/* May want to move a more generalized form of this to parsetok.c or
2422 even parser modules. */
2423
2424void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002425PyParser_ClearError(perrdetail *err)
2426{
2427 err_free(err);
2428}
2429
2430void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002431PyParser_SetError(perrdetail *err)
2432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002434}
2435
Victor Stinner7f2fee32011-04-05 00:39:01 +02002436static void
2437err_free(perrdetail *err)
2438{
2439 Py_CLEAR(err->filename);
2440}
2441
Guido van Rossuma110aa61994-08-29 12:50:44 +00002442/* Set the error appropriate to the given input error code (see errcode.h) */
2443
2444static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002445err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 PyObject *v, *w, *errtype, *errtext;
2448 PyObject *msg_obj = NULL;
2449 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 errtype = PyExc_SyntaxError;
2452 switch (err->error) {
2453 case E_ERROR:
2454 return;
2455 case E_SYNTAX:
2456 errtype = PyExc_IndentationError;
2457 if (err->expected == INDENT)
2458 msg = "expected an indented block";
2459 else if (err->token == INDENT)
2460 msg = "unexpected indent";
2461 else if (err->token == DEDENT)
2462 msg = "unexpected unindent";
2463 else {
2464 errtype = PyExc_SyntaxError;
2465 msg = "invalid syntax";
2466 }
2467 break;
2468 case E_TOKEN:
2469 msg = "invalid token";
2470 break;
2471 case E_EOFS:
2472 msg = "EOF while scanning triple-quoted string literal";
2473 break;
2474 case E_EOLS:
2475 msg = "EOL while scanning string literal";
2476 break;
2477 case E_INTR:
2478 if (!PyErr_Occurred())
2479 PyErr_SetNone(PyExc_KeyboardInterrupt);
2480 goto cleanup;
2481 case E_NOMEM:
2482 PyErr_NoMemory();
2483 goto cleanup;
2484 case E_EOF:
2485 msg = "unexpected EOF while parsing";
2486 break;
2487 case E_TABSPACE:
2488 errtype = PyExc_TabError;
2489 msg = "inconsistent use of tabs and spaces in indentation";
2490 break;
2491 case E_OVERFLOW:
2492 msg = "expression too long";
2493 break;
2494 case E_DEDENT:
2495 errtype = PyExc_IndentationError;
2496 msg = "unindent does not match any outer indentation level";
2497 break;
2498 case E_TOODEEP:
2499 errtype = PyExc_IndentationError;
2500 msg = "too many levels of indentation";
2501 break;
2502 case E_DECODE: {
2503 PyObject *type, *value, *tb;
2504 PyErr_Fetch(&type, &value, &tb);
2505 msg = "unknown decode error";
2506 if (value != NULL)
2507 msg_obj = PyObject_Str(value);
2508 Py_XDECREF(type);
2509 Py_XDECREF(value);
2510 Py_XDECREF(tb);
2511 break;
2512 }
2513 case E_LINECONT:
2514 msg = "unexpected character after line continuation character";
2515 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 case E_IDENTIFIER:
2518 msg = "invalid character in identifier";
2519 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002520 case E_BADSINGLE:
2521 msg = "multiple statements found while compiling a single statement";
2522 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 default:
2524 fprintf(stderr, "error=%d\n", err->error);
2525 msg = "unknown parsing error";
2526 break;
2527 }
2528 /* err->text may not be UTF-8 in case of decoding errors.
2529 Explicitly convert to an object. */
2530 if (!err->text) {
2531 errtext = Py_None;
2532 Py_INCREF(Py_None);
2533 } else {
2534 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2535 "replace");
2536 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002537 v = Py_BuildValue("(OiiN)", err->filename,
2538 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 if (v != NULL) {
2540 if (msg_obj)
2541 w = Py_BuildValue("(OO)", msg_obj, v);
2542 else
2543 w = Py_BuildValue("(sO)", msg, v);
2544 } else
2545 w = NULL;
2546 Py_XDECREF(v);
2547 PyErr_SetObject(errtype, w);
2548 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002549cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 Py_XDECREF(msg_obj);
2551 if (err->text != NULL) {
2552 PyObject_FREE(err->text);
2553 err->text = NULL;
2554 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002555}
2556
2557/* Print fatal error message and abort */
2558
2559void
Tim Peters7c321a82002-07-09 02:57:01 +00002560Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002561{
Victor Stinner024e37a2011-03-31 01:31:06 +02002562 const int fd = fileno(stderr);
2563 PyThreadState *tstate;
2564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 fprintf(stderr, "Fatal Python error: %s\n", msg);
2566 fflush(stderr); /* it helps in Windows debug build */
2567 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002568 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002570 else {
2571 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2572 if (tstate != NULL) {
2573 fputc('\n', stderr);
2574 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002575 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002576 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002577 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002578 }
2579
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002580#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 {
2582 size_t len = strlen(msg);
2583 WCHAR* buffer;
2584 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 /* Convert the message to wchar_t. This uses a simple one-to-one
2587 conversion, assuming that the this error message actually uses ASCII
2588 only. If this ceases to be true, we will have to convert. */
2589 buffer = alloca( (len+1) * (sizeof *buffer));
2590 for( i=0; i<=len; ++i)
2591 buffer[i] = msg[i];
2592 OutputDebugStringW(L"Fatal Python error: ");
2593 OutputDebugStringW(buffer);
2594 OutputDebugStringW(L"\n");
2595 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002596#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002598#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002599#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002601}
2602
2603/* Clean up and exit */
2604
Guido van Rossuma110aa61994-08-29 12:50:44 +00002605#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002606#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002607#endif
2608
Collin Winter670e6922007-03-21 02:57:17 +00002609static void (*pyexitfunc)(void) = NULL;
2610/* For the atexit module. */
2611void _Py_PyAtExit(void (*func)(void))
2612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002614}
2615
2616static void
2617call_py_exitfuncs(void)
2618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 if (pyexitfunc == NULL)
2620 return;
Collin Winter670e6922007-03-21 02:57:17 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 (*pyexitfunc)();
2623 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002624}
2625
Antoine Pitrou011bd622009-10-20 21:52:47 +00002626/* Wait until threading._shutdown completes, provided
2627 the threading module was imported in the first place.
2628 The shutdown routine will wait until all non-daemon
2629 "threading" threads have completed. */
2630static void
2631wait_for_thread_shutdown(void)
2632{
2633#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002634 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 PyObject *result;
2636 PyThreadState *tstate = PyThreadState_GET();
2637 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2638 "threading");
2639 if (threading == NULL) {
2640 /* threading not imported */
2641 PyErr_Clear();
2642 return;
2643 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002644 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 if (result == NULL) {
2646 PyErr_WriteUnraisable(threading);
2647 }
2648 else {
2649 Py_DECREF(result);
2650 }
2651 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002652#endif
2653}
2654
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002655#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002656static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002657static int nexitfuncs = 0;
2658
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002659int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 if (nexitfuncs >= NEXITFUNCS)
2662 return -1;
2663 exitfuncs[nexitfuncs++] = func;
2664 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002665}
2666
Guido van Rossumcc283f51997-08-05 02:22:03 +00002667static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002668call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 while (nexitfuncs > 0)
2671 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 fflush(stdout);
2674 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002675}
2676
2677void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002678Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002683}
2684
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002685static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002686initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002687{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002688#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002689 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002690#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002691#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002693#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002694#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002696#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 PyOS_InitInterrupts(); /* May imply initsignal() */
Victor Stinnerd786ad52013-07-21 13:25:51 +02002698 if (PyErr_Occurred()) {
2699 Py_FatalError("Py_Initialize: can't import signal");
2700 }
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002701}
2702
Guido van Rossum7433b121997-02-14 19:45:36 +00002703
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002704/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2705 *
2706 * All of the code in this function must only use async-signal-safe functions,
2707 * listed at `man 7 signal` or
2708 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2709 */
2710void
2711_Py_RestoreSignals(void)
2712{
2713#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002715#endif
2716#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002718#endif
2719#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002721#endif
2722}
2723
2724
Guido van Rossum7433b121997-02-14 19:45:36 +00002725/*
2726 * The file descriptor fd is considered ``interactive'' if either
2727 * a) isatty(fd) is TRUE, or
2728 * b) the -i flag was given, and the filename associated with
2729 * the descriptor is NULL or "<stdin>" or "???".
2730 */
2731int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002732Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 if (isatty((int)fileno(fp)))
2735 return 1;
2736 if (!Py_InteractiveFlag)
2737 return 0;
2738 return (filename == NULL) ||
2739 (strcmp(filename, "<stdin>") == 0) ||
2740 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002741}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002742
2743
Tim Petersd08e3822003-04-17 15:24:21 +00002744#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002745#if defined(WIN32) && defined(_MSC_VER)
2746
2747/* Stack checking for Microsoft C */
2748
2749#include <malloc.h>
2750#include <excpt.h>
2751
Fred Drakee8de31c2000-08-31 05:38:39 +00002752/*
2753 * Return non-zero when we run out of memory on the stack; zero otherwise.
2754 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002755int
Fred Drake399739f2000-08-31 05:52:44 +00002756PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 __try {
2759 /* alloca throws a stack overflow exception if there's
2760 not enough space left on the stack */
2761 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2762 return 0;
2763 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2764 EXCEPTION_EXECUTE_HANDLER :
2765 EXCEPTION_CONTINUE_SEARCH) {
2766 int errcode = _resetstkoflw();
2767 if (errcode == 0)
2768 {
2769 Py_FatalError("Could not reset the stack!");
2770 }
2771 }
2772 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002773}
2774
2775#endif /* WIN32 && _MSC_VER */
2776
2777/* Alternate implementations can be added here... */
2778
2779#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002780
2781
2782/* Wrappers around sigaction() or signal(). */
2783
2784PyOS_sighandler_t
2785PyOS_getsig(int sig)
2786{
2787#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 struct sigaction context;
2789 if (sigaction(sig, NULL, &context) == -1)
2790 return SIG_ERR;
2791 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002792#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002794/* Special signal handling for the secure CRT in Visual Studio 2005 */
2795#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 switch (sig) {
2797 /* Only these signals are valid */
2798 case SIGINT:
2799 case SIGILL:
2800 case SIGFPE:
2801 case SIGSEGV:
2802 case SIGTERM:
2803 case SIGBREAK:
2804 case SIGABRT:
2805 break;
2806 /* Don't call signal() with other values or it will assert */
2807 default:
2808 return SIG_ERR;
2809 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002810#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 handler = signal(sig, SIG_IGN);
2812 if (handler != SIG_ERR)
2813 signal(sig, handler);
2814 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002815#endif
2816}
2817
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002818/*
2819 * All of the code in this function must only use async-signal-safe functions,
2820 * listed at `man 7 signal` or
2821 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2822 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002823PyOS_sighandler_t
2824PyOS_setsig(int sig, PyOS_sighandler_t handler)
2825{
2826#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 /* Some code in Modules/signalmodule.c depends on sigaction() being
2828 * used here if HAVE_SIGACTION is defined. Fix that if this code
2829 * changes to invalidate that assumption.
2830 */
2831 struct sigaction context, ocontext;
2832 context.sa_handler = handler;
2833 sigemptyset(&context.sa_mask);
2834 context.sa_flags = 0;
2835 if (sigaction(sig, &context, &ocontext) == -1)
2836 return SIG_ERR;
2837 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002838#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 PyOS_sighandler_t oldhandler;
2840 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002841#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002843#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002845#endif
2846}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002847
2848/* Deprecated C API functions still provided for binary compatiblity */
2849
2850#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002851PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002852PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002855}
2856
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002857#undef PyParser_SimpleParseString
2858PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002859PyParser_SimpleParseString(const char *str, int start)
2860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002862}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002863
2864#undef PyRun_AnyFile
2865PyAPI_FUNC(int)
2866PyRun_AnyFile(FILE *fp, const char *name)
2867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002868 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002869}
2870
2871#undef PyRun_AnyFileEx
2872PyAPI_FUNC(int)
2873PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002875 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002876}
2877
2878#undef PyRun_AnyFileFlags
2879PyAPI_FUNC(int)
2880PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002882 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002883}
2884
2885#undef PyRun_File
2886PyAPI_FUNC(PyObject *)
2887PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2888{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002890}
2891
2892#undef PyRun_FileEx
2893PyAPI_FUNC(PyObject *)
2894PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002896 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002897}
2898
2899#undef PyRun_FileFlags
2900PyAPI_FUNC(PyObject *)
2901PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002902 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002904 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002905}
2906
2907#undef PyRun_SimpleFile
2908PyAPI_FUNC(int)
2909PyRun_SimpleFile(FILE *f, const char *p)
2910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002912}
2913
2914#undef PyRun_SimpleFileEx
2915PyAPI_FUNC(int)
2916PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002918 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002919}
2920
2921
2922#undef PyRun_String
2923PyAPI_FUNC(PyObject *)
2924PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002926 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002927}
2928
2929#undef PyRun_SimpleString
2930PyAPI_FUNC(int)
2931PyRun_SimpleString(const char *s)
2932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002933 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002934}
2935
2936#undef Py_CompileString
2937PyAPI_FUNC(PyObject *)
2938Py_CompileString(const char *str, const char *p, int s)
2939{
Georg Brandl8334fd92010-12-04 10:26:46 +00002940 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2941}
2942
2943#undef Py_CompileStringFlags
2944PyAPI_FUNC(PyObject *)
2945Py_CompileStringFlags(const char *str, const char *p, int s,
2946 PyCompilerFlags *flags)
2947{
2948 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002949}
2950
2951#undef PyRun_InteractiveOne
2952PyAPI_FUNC(int)
2953PyRun_InteractiveOne(FILE *f, const char *p)
2954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002955 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002956}
2957
2958#undef PyRun_InteractiveLoop
2959PyAPI_FUNC(int)
2960PyRun_InteractiveLoop(FILE *f, const char *p)
2961{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002962 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002963}
2964
2965#ifdef __cplusplus
2966}
2967#endif